How to get a desired result using regexp in matlab

9 visualizzazioni (ultimi 30 giorni)
sachin narain
sachin narain il 7 Mag 2018
Commentato: Giri il 9 Mag 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

Risposte (2)

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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by