Differentiate function names and variable names using regexp
2 次查看(过去 30 天)
显示 更早的评论
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;)
0 个评论
回答(1 个)
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.$&')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!