我有一串 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模式提取大括号之间的字符串的模式\{([\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]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句