【问题标题】:Get all occurrences between closest double brackets获取最近的双括号之间的所有匹配项
【发布时间】:2017-04-09 15:19:12
【问题描述】:

给定字符串$str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';

需要获取最近的开闭双花括号之间的所有匹配项。

理想的结果:

  • asd
  • 888 999
  • qw{er

如果尝试:preg_match_all('#\{\{(.*?)\}\}#', $str, $matches);

当前输出:

  • asd
  • {888 999
  • -i {{qw{er

不过,这些事件不在 最接近 双大括号之间。

问题是:什么是合适的模式?

【问题讨论】:

  • 如果输入包含{{{a}b}} 之类的内容,预期的输出是什么? {a}ba}b?
  • @Rawing - 在这种情况下预期输出:a}b

标签: php regex


【解决方案1】:

你可以使用这个模式:

\{\{(?!\{)((?:(?!\{\{).)*?)\}\}

这里的技巧是使用像(?!\{\{) 这样的负前瞻来避免匹配嵌套括号。


\{\{       # match {{
(?!\{)     # assert the next character isn't another {
(
    (?:    # as few times as necessary...
        (?!\{\{).  # match the next character as long as there is no {{
    )*?
)
\}\}       # match }}

【讨论】:

    【解决方案2】:

    Regex demo

    正则表达式: (?<=\{{2})(?!\{)[\s\w\{]+(?=\}\})

    (?=\}\})前面应该包含双花括号

    (?<=\{{2}) 后面应该包含花括号

    (?!\{) 不应包含花括号一个花括号后面两个匹配

    PHP 代码:

    $str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';
    preg_match_all("/(?<=\{{2})(?!\{)[\s\w\{]+(?=\}\})/",$str,$matches);
    print_r($matches);
    

    输出:

    Array
    (
        [0] => Array
            (
                [0] => asd
                [1] => 888 999
                [2] => qw{er
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多