to find variables in a string
조회 수: 11 (최근 30일)
이전 댓글 표시
Hello,
this may be a simple problem. but i cant figure it out.
I have a string which is acquired from an .m file through fgetl function. How can i find the existence of any variable or built-in function inside that string? is there built-in function for searching variable name or built-in function name inside a string?
-obli
댓글 수: 0
채택된 답변
Richard Zapor
2012년 6월 1일
For variables use symvar(str). It will create a cell array of variable names.
Finding "built-in" functions can be performed using cellfun(@exist,cell_array_input)==5.
The 5 denotes built-in low level functions. A value of 2 is likely what you also want and these are the Toolbox functions like "filter2", "interp2" or "smooth3".
Another form to use directly on a string is of the form exist('log2','builtin').
To create the cell_array_input from a string use:
cell_array_input=regexp(str, '[a-zA-Z][a-zA-Z0-9]+','match')
This forces the first letter to be alphanumeric but allows functions like interp2 to be captured
댓글 수: 2
Felix Mardt
2020년 11월 20일
Another small adjustment: single letter variables will not be returned. I am using
[a-zA-Z]([a-zA-Z0-9_]+)?
to cover them
추가 답변 (2개)
Walter Roberson
2012년 5월 20일
There is no routine that will check for built-in function names. This has been requested as an enhancement, I believe.
You can use regexp() to search for strings that look like variable names. A variable name must start with a Latin (English) letter, and each character after that must be a Latin (English) letter or a Latin (English) digit, or the character underscore, and must be at most 63 characters. Also, a variable name must not be a keyword. Keywords can be tested for using iskeyword()
What do you want your routine to do if there is a string such as "_key" (begins with an underscore and so is not a valid variable name) or "23skidoo" (begins with a digit and so is not a valid variable name) or "prêt" (contains a non-Latin letter and so is not a valid variable name) ?
You indicate that your string is from a .m file: does that mean you have to deal with quoted strings, and comments, and that you do not want to identify variable-name-like portions inside strings or comments? If that is the case, then your task becomes harder.
What is the purpose of your analysis? If you are attempting to determine whether a string is "safe" to evaluate, then security practice says that always always only accept strings that you are certain are safe: if you construct security code by rejecting patterns you know to be unsafe then you will very likely miss something that is unsafe (possibly it did not become unsafe until after you wrote your code.)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!