Regex 如何找到下一个不平衡支撑?
下面的正则表达式捕获到最后一次平衡的Regex 如何找到下一个不平衡支撑?,regex,perl,recursion,Regex,Perl,Recursion,下面的正则表达式捕获到最后一次平衡的}之前的所有内容 现在,哪个正则表达式能够捕获到下一个不平衡}之前的所有内容?换句话说,我怎样才能得到。。。{three{four}}five}来自$str而不仅仅是。。。{三{四} my $str = "one two {three {four}} five} six"; if ( $str =~ / ( .*? { (?>
}
之前的所有内容
现在,哪个正则表达式能够捕获到下一个不平衡}
之前的所有内容?换句话说,我怎样才能得到。。。{three{four}}five}
来自$str
而不仅仅是。。。{三{四}
my $str = "one two {three {four}} five} six";
if ( $str =~ /
(
.*?
{
(?> [^{}] | (?-1) )+
}
)
/sx
)
{
print "$1\n";
}
所以你想要匹配
[noncurlies [block noncurlies [...]]] "}"
其中,块
是
"{" [noncurlies [block noncurlies [...]]] "}"
作为语法:
start : text "}"
text : noncurly* ( block noncurly* )*
block : "{" text "}"
noncurly : /[^{}]/
作为正则表达式(5.10+):
作为正则表达式(5.10+):
/
^((?&TEXT)\})
(?(定义)
(?[^{}]*(?:(?&BLOCK)[^{}]*))
(?\{(?&TEXT)\})
)
/x
它可以工作。不过,我需要一些时间来理解最里面的诀窍。只要把(?-1)
想象成语法中的文本。添加了替代正则表达式解决方案我可以编辑你的答案来添加一个间断,(?是的。你知道如何改进它吗?
/
^
(
(
[^{}]*
(?:
\{ (?-1) \}
[^{}]*
)*
)
\}
)
/x
/
^ ( (?&TEXT) \} )
(?(DEFINE)
(?<TEXT> [^{}]* (?: (?&BLOCK) [^{}]* )* )
(?<BLOCK> \{ (?&TEXT) \} )
)
/x