How to use regex to match elements not followed by...?
How can I match this string?
${test {0}}
I need to match everything between ${
and }
w开发者_StackOverflow中文版here }
is not preceded by a number, so I can retrieve test {0}
.
Is it possible to match with a regex pattern alone?
Samples:
${any string} == any string
${string - {x} == string - {x
${{0} a} == {0} a
${a {1} b {3} c {2} d {0}} == a {1} b {3} c {2} d {0}
You can ensure such a criteria using a negative look behind like this
\$\{(.*)(?<!\d)\}
You can see it online here on Regexr.
Your string is in group 1.
The negative lookahead ensures that it matches only on a }
that is not preceded by a digit.
This works for your test case, but you need to be more clear about how the data you need to capture could vary if you want a better general regex
The regex:
/\${(.*[^0-9])}/
In Javascript:
alert( "${test {0}}".match( /\${(.*[^0-9])}/ )[1] )
(Edited following up on your examples...) Like so:
/\$\{((?:.+?|\{\d+\})+?)\}/
Expect gargantuan backtracking, though...
How about : /\$\{(.*)\}/
Here is a perl script that do the job with the given examples :
#!/usr/bin/perl
use Modern::Perl;
my @l = ('${any string}','${string - {x}','${{0} a}','${a {1} b {3} c {2} d {0}}');
my $re = qr/\$\{(.*)\}/;
foreach(@l) {
say $1 if $_ =~ $re;
}
output:
any string
string - {x
{0} a
a {1} b {3} c {2} d {0}
Not sure which in which language you need this solution but following works for me in PHP:
$arr = array('${test {0}}', '${any string}', '${string - {x}', '${{0} a}', '${a {1} b {3} c {2} d {0}}');
foreach ($arr as $s) {
if (preg_match('~\$\{(.+?[^\d])}~', $s, $m ) > 0)
var_dump($s . ' == ' . $m[1]);
}
OUTPUT
string(23) "${test {0}} == test {0}"
string(27) "${any string} == any string"
string(29) "${string - {x} == string - {x"
string(17) "${{0} a} == {0} a"
string(53) "${a {1} b {3} c {2} d {0}} == a {1} b {3} c {2} d {0}"
(?<={)([^{}]*({\d+})*[^{}]*)+(?=})
It has been tested with RAD Software Regular Expression Designer.. This regex works for .NET and java environment..
You should use this regex for Javascript..
{([^{}]*({\d+})*[^{}]*)+}
精彩评论