问题
The regex below captures everything up to the last balanced }
.
Now, what regex would be able to capture everything up to the next unbalanced }
? In other words, how can I can get ... {three {four}} five}
from $str
instead of just ... {three {four}}
?
my $str = "one two {three {four}} five} six";
if ( $str =~ /
(
.*?
{
(?> [^{}] | (?-1) )+
}
)
/sx
)
{
print "$1\n";
}
回答1:
So you want to match
[noncurlies [block noncurlies [...]]] "}"
where a block
is
"{" [noncurlies [block noncurlies [...]]] "}"
As a grammar:
start : text "}"
text : noncurly* ( block noncurly* )*
block : "{" text "}"
noncurly : /[^{}]/
As a regex (5.10+):
/
^
(
(
[^{}]*
(?:
\{ (?-1) \}
[^{}]*
)*
)
\}
)
/x
As a regex (5.10+):
/
^ ( (?&TEXT) \} )
(?(DEFINE)
(?<TEXT> [^{}]* (?: (?&BLOCK) [^{}]* )* )
(?<BLOCK> \{ (?&TEXT) \} )
)
/x
来源:https://stackoverflow.com/questions/32101294/how-to-find-the-next-unbalanced-brace