【问题标题】:Regex pattern to get string between curly braces正则表达式模式在花括号之间获取字符串
【发布时间】:2015-07-05 08:59:57
【问题描述】:

我有一个字符串The quick brown {fox, dragon, dinosaur} jumps over the lazy {dog, cat, bear, {lion, tiger}}.

我想获取花括号之间的所有字符串。必须忽略花括号内的花括号。 PHP 数组中的预期输出为

[0] => fox, dragon, dinosaur
[1] => dog, cat, bear, {lion, tiger}

我尝试了 Mar 回答的 Regex pattern extract string between curly braces and exclude curly braces 中的 \{([\s\S]*)\} 这种模式,但似乎这种模式在大括号之间获取所有字符串,而不会拆分不相关的文本(不确定要使用正确的词)。 这是上面模式的输出

fox, jumps, over} over the lazy {dog, cat, bear, {lion, tiger}}

从上面的句子中打印预期输出的最佳正则表达式模式是什么?

【问题讨论】:

标签: php regex pcre


【解决方案1】:

正如 anubhava 所说,您可以使用递归模式来做到这一点。

但是,他的版本相当“慢”,并没有涵盖所有情况。

我会亲自使用这个正则表达式:

#({(?>[^{}]|(?0))*?})#

如您所见:http://lumadis.be/regex/test_regex.php?id=2516 它快了很多;并匹配更多结果。

那么,它是如何工作的?

/
  (              # capturing group
    {            # looks for the char '{'
    (?>          # atomic group, engine will never backtrack his choice
        [^{}]    #   looks for a non-'{}' char
      |          # or
        (?0)     #   re-run the regex in a subroutine to match a subgroup
    )*?          # and does it as many time as needed
    }            # looks for the char '}'
  )              # ends the capture
/x

为什么我使用“*”?

添加“?”到 '*' 使它不贪婪。如果您在那里使用贪婪量词,引擎将启动比使用不贪婪量词更多的子程序。 (如果您需要更多解释,请告诉我)

【讨论】:

    【解决方案2】:

    您可以在 PHP 中使用这种递归正则表达式模式:

    $re = '/( { ( (?: [^{}]* | (?1) )* ) } )/x'; 
    $str = "The quick brown {fox, dragon, dinosaur} jumps over the lazy {dog, cat, bear, {lion, tiger}}."; 
    
    preg_match_all($re, $str, $matches);
    print_r($matches[2]);
    

    RegEx Demo

    【讨论】:

    • 非常感谢。你拯救了我的一天:)
    • -01 有很多重复,这个答案甚至没有解释原理。
    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2013-07-20
    相关资源
    最近更新 更多