How to get a desired result using regexp in matlab

9 Ansichten (letzte 30 Tage)
sachin narain
sachin narain am 7 Mai 2018
Kommentiert: Giri am 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

Antworten (2)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by