Simplify a string with MATLAB script
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Lucas S
el 27 de Feb. de 2020
Comentada: Lucas S
el 28 de Feb. de 2020
Hello !
I have a string format which looks like this (this is not always 'A' before '_' and numbers) :
Eq = 'A_1+((A_2+A_3)&(A_4+A_5))+A_6';
How can i simplify the string like this (with a script) :
Eq = 'A_(1+((2+3)&(4+5))+6)'
For me the simplest way would be to delete all 'A_' iteration except the first one and to add a '(' after the first 'A_' but i don't know how to do it in a script.
Thank you in advance for your help !
Edit : After Stephen answer review, i realized i missed a detail : sometimes the string can be like this :
'A_number_1+((A_number_2+A_number_3)&(A_number_+A_number_5))+A_number_6';
==> 'A_number_(1+((2+3)&(4+5))+6)'
With multiple string for example : 'String_String_String_1' . Is there anyway to delete string and '_' behind a number ?
0 comentarios
Respuesta aceptada
Stephen23
el 27 de Feb. de 2020
Editada: Stephen23
el 27 de Feb. de 2020
>> Eq = 'A_1+((A_2+A_3)&(A_4+A_5))+A_6';
>> Fq = regexprep(Eq, '^([A-Z]+_)(.*)', '$1\(${strrep($2,$1,'''')}\)')
Fq =
A_(1+((2+3)&(4+5))+6)
10 comentarios
Stephen23
el 28 de Feb. de 2020
Editada: Stephen23
el 28 de Feb. de 2020
"'Or use regexp but for me regexp is only for same format's same length's string (i'm probably wrong)"
I can't see anything in the regular expression that restricts it to "same length's string" as you write, it adapts exaclty to the the length of the leading name, with any number of 'string_' repetitions.
When I run it on all of your example strings, I get the expected outputs, e.g.:
>> Eq = 'A_number_1+((A_number_2+A_number_3)&(A_number_4+A_number_5))+A_number_6';
>> Fq = regexprep(Eq, '^(\w+?)(\d+\W.*)', '$1\(${strrep($2,$1,'''')}\)')
Fq =
A_number_(1+((2+3)&(4+5))+6)
and
>> Eq = 'string_string_number_1+((string_string_number_2+string_string_number_3)&(string_string_number_4+string_string_number_5))+string_string_number_6';
>> Fq = regexprep(Eq, '^(\w+?)(\d+\W.*)', '$1\(${strrep($2,$1,'''')}\)')
Fq =
string_string_number_(1+((2+3)&(4+5))+6)
etc. etc.
Please show me a single example of my code that does not give the expected output, so that I can check it.
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!