正则表达式模式获取花括号之间的字符串

Regex pattern to get string between curly braces

我有一个字符串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 回答的 中的这种模式 \{([\s\S]*)\},但似乎这种模式将所有字符串都放在花括号之间,而没有拆分不相关的文本(不确定使用正确的词)。 这是上述模式的输出

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

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

您可以在 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

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

然而,他的版本很漂亮"slow",并没有涵盖所有情况。

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

#({(?>[^{}]|(?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

为什么我用了“*”?

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