除了模式之外的一切

Everything but pattern

我想捕获 2 对大括号之间的所有内容 {{ ... }}

我已有的就是这个

/{{([^{}]+)}}/i
here with some spaces, for better reading:
/  {{  [^{}]+  }}  /i 

但这显然不会让我做类似{{ function(){ echo 1234; }; }}

的事情

所以我的问题是:如何排除模式而不是列表?

您需要构建一个递归子模式来匹配平衡的大括号。

({[^{}]*+(?:(?1)[^{}]*)*})

所以要将其整合到您的整个模式中:

{({([^{}]*+(?:(?1)[^{}]*)*+)})}

现在您要查找的内容在捕获组 2 中

子模式详细信息:

(               # open the capture group 1
    {           # literal {
    [^{}]*+     # all that is not a curly bracket (possessive quantifier)
    (?:         # non capturing group
        (?1)    # recursion: `(?1)` stands for the subpattern
                # inside the capture group 1 (so the current subpattern)
        [^{}]*  #
    )*+         # repeat as needed the non capturing group
    }           # literal }
)               # close the capture group 1

这里使用所有格量词来防止括号不平衡时回溯过多。

这种方式的优点是无论嵌套括号的级别如何,它都有效,请参见示例:

demo

这是正则表达式。

\{{2}(.*?)\}{2}

\ 正在转义第一个卷曲,因为您想找到实际字符。下一个打开和关闭卷曲告诉它要找到多少个前一个字符。句点表示任何字符。与星号和问号配对的意思是找到下一个 2 个大括号之前的所有内容(2 又是因为 {2})。有问题吗?