How to get a desired result using regexp in matlab

10 次查看(过去 30 天)
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

回答(2 个)

Rik
Rik 2018-5-7
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 2018-5-7
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 个评论
Stephen23
Stephen23 2018-5-7
^\( % 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 2018-5-9
aah ok thanks.. i did not realise that you were replacing the string. Thanks a lot Stephen.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by