获取括号之间的所有文本但跳过嵌套括号
get all text between bracket but skip nested bracket
我正在尝试弄清楚如何获取两个括号标签之间的文本,但不要在第一次结束时停止)
__('This is a (TEST) all of this i want') i dont want any of this;
我目前的模式是__\((.*?)\)
这给了我
__('This is a (TEST)
但我想要
__('This is a (TEST) all of this i want')
谢谢
您忘记在正则表达式中转义两个括号:__\((.*)\)
;
查看regex101.com。
使用模式 __\((.*)?\)
.
\
对括号进行转义以捕获文字括号。然后捕获该组括号内的所有文本。
您可以使用正则表达式子例程来匹配 __
:
之后嵌套括号内的文本
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
参见regex demo。
详情
__
- __
子串
(\(((?:[^()]++|(?1))*)\))
- 第 1 组(将使用 (?1)
子例程递归):
\(
- 一个 (
字符
((?:[^()]++|(?1))*)
- 第 2 组捕获除 (
和 )
之外的任何 1+ 个字符的 0 次或多次重复,或者整个第 1 组模式被递归
\)
- 一个 )
字符。
参见 PHP demo:
$s = "__('This is a (TEST) all of this i want') i dont want any of this; __(extract this)";
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
// => Array ( [0] => 'This is a (TEST) all of this i want' [1] => extract this )
我正在尝试弄清楚如何获取两个括号标签之间的文本,但不要在第一次结束时停止)
__('This is a (TEST) all of this i want') i dont want any of this;
我目前的模式是__\((.*?)\)
这给了我
__('This is a (TEST)
但我想要
__('This is a (TEST) all of this i want')
谢谢
您忘记在正则表达式中转义两个括号:__\((.*)\)
;
查看regex101.com。
使用模式 __\((.*)?\)
.
\
对括号进行转义以捕获文字括号。然后捕获该组括号内的所有文本。
您可以使用正则表达式子例程来匹配 __
:
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
参见regex demo。
详情
__
-__
子串(\(((?:[^()]++|(?1))*)\))
- 第 1 组(将使用(?1)
子例程递归):\(
- 一个(
字符((?:[^()]++|(?1))*)
- 第 2 组捕获除(
和)
之外的任何 1+ 个字符的 0 次或多次重复,或者整个第 1 组模式被递归\)
- 一个)
字符。
参见 PHP demo:
$s = "__('This is a (TEST) all of this i want') i dont want any of this; __(extract this)";
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
print_r($matches[2]);
}
// => Array ( [0] => 'This is a (TEST) all of this i want' [1] => extract this )