我有以下字符串:
"{My {formatted {hi|hello}|formate{hi|hello} } {option 1|option 2|option 3}}";
Run Code Online (Sandbox Code Playgroud)
我想在"{"和"}"括号之间找到结果.
结果也应来自外层,而不是{hi|hello}:
"My {formatted {hi|hello}|formate{hi|hello} } {option 1|option 2|option 3}"
Run Code Online (Sandbox Code Playgroud)
您可以使用以下模式从不确定级别的嵌套括号中提取最外层内容:
$pattern = '~{((?>[^{}]++|(?R))+)}~';
Run Code Online (Sandbox Code Playgroud)
在哪里(?R)意味着重复整个模式.这是一种递归方法.
如果在较大的表达式中需要使用相同的子模式,则必须使用:
({((?>[^{}]++|(?-2))+)})因为它(?-2)是左侧第二个捕获组的相对引用(第一个在此处).
图案细节:
( # first capturing group
{ # literal {
( # second capturing group (what you are looking for)
(?> # atomic group
[^{}]++ # all characters except { and }, one or more time
| # OR
(?-2) # repeat the first capturing group (second on the left)
)+ # close the atomic group, repeated 1 or more time
) # close the second capturing group
} # literal }
) # close the first capturing group
Run Code Online (Sandbox Code Playgroud)