我想获取input()内部的数组格式的子字符串。我使用了preg_match,但无法获取整个表达式。它在第一个)处停止。我如何匹配整个子字符串?谢谢。
input()
preg_match
)
$input="input([[1,2,nc(2)],[1,2,nc(1)]])"; preg_match('@^([^[]+)?([^)]+)@i',$input, $output);
期望是:
'[[1,2,nc(2)],[1,2,nc(1)]]'
olqngx591#
这个模式匹配你想要的字符串(也有开始单词≠ 'input':
@^(.+?)\((.+?)\)$@i
^(.+?) => find any char at start (ungreedy option) \) => find one parenthesis (.+?) => find any char (ungreedy option) => your desired match \) => find last parenthesis
yks3o0rb2#
试试这个:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])"; preg_match('/input\((.*?\]\])\)/',$input,$matches); print_r($matches);
vsmadaxz3#
你想把它作为一个字符串吗?使用这个简单的正则表达式:
preg_match('/\((.*)\)$/',$input,$matches);
vuktfyat4#
其他答案均未有效/准确回答您的问题:要获得最快的精确模式,请使用:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])"; echo preg_match('/input\((.*)\)/i',$input,$output)?$output[1]:''; // notice index ^
或者,对于通过避免捕获组而使用内存减少50%的稍慢模式,请使用:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])"; echo preg_match('/input\(\K(.*)(?=\))/i',$input,$output)?$output[0]:''; // notice index ^
两种方法将提供相同的输出:[[1,2,nc(2)],[1,2,nc(1)]]使用贪婪的*限定符允许模式移动传递的嵌套括号,并匹配整个预期的子字符串。在第二种模式中,\K重置匹配的起始点,(?=\))是一个肯定的前瞻,确保匹配整个子字符串,而不包括结尾的右括号。编辑:撇开所有正则表达式卷积不谈,因为你知道你想要的子串被 Package 在input(和)中,最好、最简单的方法是非正则表达式方法...
[[1,2,nc(2)],[1,2,nc(1)]]
*
\K
(?=\))
input(
$input="input([[1,2,nc(2)],[1,2,nc(1)]])"; echo substr($input,6,-1); // output: [[1,2,nc(2)],[1,2,nc(1)]]
好的。
4条答案
按热度按时间olqngx591#
这个模式匹配你想要的字符串(也有开始单词≠ 'input':
yks3o0rb2#
试试这个:
vsmadaxz3#
你想把它作为一个字符串吗?使用这个简单的正则表达式:
vuktfyat4#
其他答案均未有效/准确回答您的问题:
要获得最快的精确模式,请使用:
或者,对于通过避免捕获组而使用内存减少50%的稍慢模式,请使用:
两种方法将提供相同的输出:
[[1,2,nc(2)],[1,2,nc(1)]]
使用贪婪的
*
限定符允许模式移动传递的嵌套括号,并匹配整个预期的子字符串。在第二种模式中,
\K
重置匹配的起始点,(?=\))
是一个肯定的前瞻,确保匹配整个子字符串,而不包括结尾的右括号。编辑:撇开所有正则表达式卷积不谈,因为你知道你想要的子串被 Package 在
input(
和)
中,最好、最简单的方法是非正则表达式方法...好的。