How to get a desired result using regexp in matlab

9 visualizaciones (últimos 30 días)
sachin narain
sachin narain el 7 de Mayo de 2018
Comentada: Giri el 9 de Mayo de 2018
I am evaluating a matlab expression: I have an expression like this:
exp2 = '[^(]+.*[^)]+'; I have a variable str ='(1,2,3)' I want to evaluate a regexp as follows:
regexp(str,exp2,'match');
and this works and i get a result:'1,2,3'
the same goes for when str ='(1m)' result is '1m'
But when str ='(1)' the result is { }
What should i do to get a result ='1'
Kindly help me with this.Thank you in advance

Respuestas (2)

Rik
Rik el 7 de Mayo de 2018
Just like Stephen, I would also suggest changing your expression.
exp2 = '[^()]';
str1 ='(1,2,3)';
str2='(1)';
[start_idx,end_idx]=regexp(str1,exp2);
str1(start_idx)
[start_idx,end_idx]=regexp(str2,exp2);
str2(start_idx)

Stephen23
Stephen23 el 7 de Mayo de 2018
Why do you need regular expressions for this? Why not just str(2:end-1) ?:
>> str = '(1,2,3)';
>> str(2:end-1)
ans = 1,2,3
>> str = '(1m)';
>> str(2:end-1)
ans = 1m
>> str = '(1)';
>> str(2:end-1)
ans = 1
Or perhaps use regexprep, which would make your regular expression simpler (because it is easier to match what you don't want):
>> str = '(1,2,3)';
>> regexprep(str,'^\(|\)$','')
ans = 1,2,3
>> str = '(1m)';
>> regexprep(str,'^\(|\)$','')
ans = 1m
>> str = '(1)';
>> regexprep(str,'^\(|\)$','')
ans = 1
  3 comentarios
Stephen23
Stephen23 el 7 de Mayo de 2018
^\( % matches parenthesis at start of string
| % or
\)$ % matches parenthesis at end of string
Any match is replaced by '', i.e. is removed from the input.
Giri
Giri el 9 de Mayo de 2018
aah ok thanks.. i did not realise that you were replacing the string. Thanks a lot Stephen.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings 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