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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by