Differentiate function names and variable names using regexp

조회 수: 1 (최근 30일)
Zacharias Zschenderlin
Zacharias Zschenderlin 2018년 2월 6일
답변: Achyutha Hosahalli 2018년 2월 12일
Hi,
I want to use regexprep the following way:
- Input String: A Matlab command which contains function names and variables
- Output: The same command, but every variable name should start with 'data.'
Example:
- Input String: 3600*mean(Variable_A1)/Variable_B2(1:3)
- Desired Output: 3600*mean(data.Variable_A1)/data.Variable_B2(1:3)
I tried this code:
input = '3600*mean(Variable_A1)/Variable_B2(1:3)';
output = regexprep(input,'[a-zA-Z][a-zA-Z0-9_]*(?![a-zA-Z0-9_]*[\(])','data.$&');
The challenge is to detect "mean" as a function and NOT add "data." in front. With my code I detect every name which is followed by "(" as a function. However this works only for "mean(..." and not for "variable(1:3)".
I found that with dynamic regular expressions it is possible to evaluate a MATLAB command within regexprep (??@cmd). Maybe the function and variable names could be differentiated using "exist". However I´m not very good at regular expressions and could find no way to get it to work. Can someone help? Thanks!!!
P.S. I'm looking for an elegant, short command here. I was able to create a lengthy workaround by myself;)

답변 (1개)

Achyutha Hosahalli
Achyutha Hosahalli 2018년 2월 12일
Though the below command does not differentiate between function names and variable names, you can use it if all your variables contain '_'(underscore) and none of the functions contain it.
output = regexprep(input,'\w*(?=\x5F)','data.$&')

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by