Differentiate function names and variable names using regexp

3 views (last 30 days)
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;)

Answers (1)

Achyutha Hosahalli
Achyutha Hosahalli on 12 Feb 2018
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.$&')

Community Treasure Hunt

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

Start Hunting!