我有一个字符串 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}
我尝试了来自 Regex pattern extract string between curly braces and exclude curly braces 的这种模式 \{([\s\S]*)\}
由 Mar 回答,但似乎这种模式在大括号之间获取所有字符串而不拆分不相关的文本(不确定使用正确的词)。
这是上面模式的输出
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]);
关于php - 正则表达式模式获取花括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29886743/