Parsing text without eval

5 visualizaciones (últimos 30 días)
Nieves Lopez
Nieves Lopez el 21 de Mzo. de 2023
Comentada: Nieves Lopez el 21 de Mzo. de 2023
Hello,
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 comentarios
Rik
Rik el 21 de Mzo. de 2023
Your requirements seem to conflict. You want to evaluate arbitrary code, but you don't want to use the function that evaluates arbitrary code.
Even if you use the recently introduced option to restrict what str2num does (to make it safer than eval) it will fail on more complicated things like you posted.
text = '{[1 2], [3 4] ''someText'' {5, [6, 7]}}'
text = '{[1 2], [3 4] 'someText' {5, [6, 7]}}'
X = str2num(text,Evaluation="restricted")
X = []
I suspect you will have to write you own parser.
Nieves Lopez
Nieves Lopez el 21 de Mzo. de 2023
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.

Iniciar sesión para comentar.

Respuestas (2)

Adam Danz
Adam Danz el 21 de Mzo. de 2023
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));
fprintf(fid,'%s',text);
clear fidCleanup
run(tempFile)
delete(tempFile)
Result
ans =
1×4 cell array
{[1 2]} {[3 4]} {'someText'} {1×2 cell}
  4 comentarios
Nieves Lopez
Nieves Lopez el 21 de Mzo. de 2023
Thank you again for your response. In the code, when Matlab runs tempFile it only shows the filename by the command window (as the content of any other variable). Anyway, when generating code in C with codegen, the compiler would look for a file named temp.m and would not find it.
Adam Danz
Adam Danz el 21 de Mzo. de 2023
Yeah, this wouldn't work outside of MATLAB. I missed that you were compiling your code.

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 21 de Mzo. de 2023

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by