如何找到下一个不平衡支架?

时间:2015-08-19 16:49:08

标签: regex perl recursion

下面的正则表达式捕获所有内容,直到最后一个平衡}

现在,正则表达式能够捕获到下一个不平衡 }的所有内容?换句话说,我怎样才能从... {three {four}} five}而不仅仅$str获取... {three {four}}

my $str = "one two {three {four}} five} six";

if ( $str =~ /
              (
                .*?
                {
                  (?> [^{}] | (?-1) )+
                }
              )
            /sx
   )
   {
     print "$1\n";
   }

1 个答案:

答案 0 :(得分:3)

所以你要匹配

[noncurlies [block noncurlies [...]]] "}"

其中block

"{" [noncurlies [block noncurlies [...]]] "}"

作为语法:

start    : text "}"
text     : noncurly* ( block noncurly* )*
block    : "{" text "}"
noncurly : /[^{}]/

作为正则表达式(5.10 +):

/
   ^
   (
      (
         [^{}]*
         (?:
             \{ (?-1) \}
             [^{}]*
         )*
      )
      \}
   )
/x

作为正则表达式(5.10 +):

/
   ^ ( (?&TEXT) \} )

   (?(DEFINE)
      (?<TEXT>   [^{}]* (?: (?&BLOCK) [^{}]* )*   )
      (?<BLOCK>  \{ (?&TEXT) \}                   )
   )
/x