How to get a desired result using regexp in matlab

10 vues (au cours des 30 derniers jours)
sachin narain
sachin narain le 7 Mai 2018
Commenté : Giri le 9 Mai 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

Réponses (2)

Rik
Rik le 7 Mai 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 le 7 Mai 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 commentaires
Stephen23
Stephen23 le 7 Mai 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 le 9 Mai 2018
aah ok thanks.. i did not realise that you were replacing the string. Thanks a lot Stephen.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by