- avoids the problem with "greedies"
- better performance; easier to evaluate
Help using Regexp:
16 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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!
0 Commenti
Risposta accettata
per isakson
il 23 Mag 2018
Modificato: per isakson
il 23 Mag 2018
One way
>> str='Some.Text {a1=v1 a2=v2}';
>> cac = regexp( str, '(?<={)[^}]+(?=})', 'once', 'match' )
cac =
a1=v1 a2=v2
>>
[^}]+ is better than .+ because
'(?<=\{)[^}]+(?=\})' it doesn't hurt to escape {} if in doubt whether the are special characters.
3 Commenti
per isakson
il 23 Mag 2018
Modificato: per isakson
il 23 Mag 2018
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,
- the Matlab documentation
- Welcome to Regular-Expressions.info, The Premier website about Regular Expressions is good. It has a book review page.
- regular expression 101 is a free tool in the cloud. I use it for experimenting. But one must avoid features that are not in Matlab.
- There are some Matlab specific tools in the File Exchange
- Mastering Regular Expressions if you want to become an expert.
- and best of all is Understanding and Using Regular Expressions
per isakson
il 23 Mag 2018
Modificato: per isakson
il 24 Mag 2018
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
Più risposte (0)
Vedere anche
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!