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

标签 php regex pcre

我有一个字符串 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]);

RegEx Demo

关于php - 正则表达式模式获取花括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29886743/

相关文章:

pcre - 使用 PCRE 支持重建 uwsgi

php - 如何在 drupal 7 中实现 hook_theme?

php - 无法在 PHP 中删除或更新行?

Java 正则表达式用于包装除某些给定字符之外的所有内容

c# - 如何使用 (?!...) 正则表达式模式跳过整个不匹配的部分?

regex - 删除美国电话号码及其分机号码的格式

c - IIRF 中的堆栈溢出(C 程序,ISAPI)

pcre - snort 的 pcre 规则选项中的/R 是什么意思?

php - 一选不发布所选选项

php - 解压缩或膨胀 php ://input stream?