如何找到下一个不平衡的支撑? [英] How to find the next unbalanced brace?

查看:45
本文介绍了如何找到下一个不平衡的支撑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的正则表达式捕获了最后一个平衡的 } 之前的所有内容.

The regex below captures everything up to the last balanced }.

现在,什么正则表达式能够捕获下一个不平衡 } 之前的所有内容?换句话说,我怎样才能从 $str 获得 ... {three {four}} Five} 而不是 ... {three {four}} Five}}}?

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";
   }

推荐答案

所以你要匹配

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

block 在哪里

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

作为语法:

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

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

As a regex (5.10+):

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

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

As a regex (5.10+):

/
   ^ ( (?&TEXT) \} )

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

这篇关于如何找到下一个不平衡的支撑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆