How to find the next unbalanced brace?

别等时光非礼了梦想. 提交于 2020-02-03 08:39:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!