Parsing text without eval

조회 수: 3(최근 30일)
Nieves Lopez
Nieves Lopez 2023년 3월 21일
댓글: Nieves Lopez 2023년 3월 21일
I have some strings with values that I would like to parse. The easiest way is to use the eval function. However, I can not use it since the code is going to be compiled. Any idea on how to do this without having to parse each of the characters?
As an example, one of the string could be like this:
>> text = '{[1 2], [3 4] ''someText'' {5, [6, 7]}}'
text =
{[1 2], [3 4] 'someText' {5, [6, 7]}}
>> eval(text)
ans =
1×4 cell array
[1×2 double] [1×2 double] 'someText' {1×2 cell}
Thank you in advance!
  댓글 수: 2
Nieves Lopez
Nieves Lopez 2023년 3월 21일
Not so arbitrary code, only with numbers, strings, cells. No function calls. I was just wondering if I'm missing any function that can help me.

댓글을 달려면 로그인하십시오.


Adam Danz
Adam Danz 2023년 3월 21일
You could write the string to an m-file and then run the m-file, though this has the same flaws/risks as eval.
This demo creates a file temp.m, writes the string text to the file, runs the file, and then deletes the temporary file.
text = '{[1 2], [3 4] ''someText'' {5, [6, 7]}}'
tempFile = 'temp.m';
fid = fopen(tempFile,'w');
fidCleanup = onCleanup(@()fclose(fid));
clear fidCleanup
ans =
1×4 cell array
{[1 2]} {[3 4]} {'someText'} {1×2 cell}
  댓글 수: 4
Adam Danz
Adam Danz 2023년 3월 21일
Yeah, this wouldn't work outside of MATLAB. I missed that you were compiling your code.

댓글을 달려면 로그인하십시오.

Image Analyst
Image Analyst 2023년 3월 21일


Find more on Variables in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by