Help using Regexp:

조회 수: 10 (최근 30일)
Ajpaezm
Ajpaezm 2018년 5월 23일
편집: per isakson 2018년 5월 24일
Hello,
I'm a bit confused on how to use regexp to get information that's between braces. For example, I have the following text:
str='Some.Text {a1=v1 a2=v2}';
val=regexp(str, ?, 'match', 'once')
In "?" should be a like a pattern of special characters (lookaheads, lookbehinds, non-greedys, etc) but I don't know how to make it work to just extract everything inside {}.
Can someone help me?
Thanks in advance!

채택된 답변

per isakson
per isakson 2018년 5월 23일
편집: per isakson 2018년 5월 23일
One way
>> str='Some.Text {a1=v1 a2=v2}';
>> cac = regexp( str, '(?<={)[^}]+(?=})', 'once', 'match' )
cac =
a1=v1 a2=v2
>>
[^}]+ is better than .+ because
  • avoids the problem with "greedies"
  • better performance; easier to evaluate
'(?<=\{)[^}]+(?=\})' it doesn't hurt to escape {} if in doubt whether the are special characters.
  댓글 수: 3
per isakson
per isakson 2018년 5월 23일
편집: per isakson 2018년 5월 23일
There are many good resources on the Internet. However, Matlab has it's own regular expression flavor. It's close to a subset of PCRE, (PERL Compatible RE). (Not the latest version of PRCE though.) Thus,
per isakson
per isakson 2018년 5월 23일
편집: per isakson 2018년 5월 24일
btw:
xpr = [
'(?<={) ' ... % look behind for literal {
'[^}]+ ' ... % one or more of anything, but literal }
'(?=}) ' ... % look ahead for literal }
];
xpr( isspace(xpr) ) = [];
cac = regexp( str, xpr, ... );
I find this way of writing regular expressions good. It makes me think more and experiment less; it helps me avoid falling into an infinite "trial-and-error-loops".
  • "space" is a bit of a problem. I write space as \x20
  • The final look ahead isn't needed, since + is greedy

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by