我想获取一个数组格式的子字符串,该子字符串位于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)]]'
此模式与所需的字符串匹配(也带有起始词≠"input":
@^(.+?)'((.+?)')$@i
3v4l.org 演示
^(.+?) => find any char at start (ungreedy option)
') => find one parenthesis
(.+?) => find any char (ungreedy option) => your desired match
') => find last parenthesis
试试这个:
$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('/input'((.*?']'])')/',$input,$matches);
print_r($matches);
$matches[1]将包含您需要的完整结果。希望这有效。
你想把它纯粹作为一个字符串吗?使用这个简单的正则表达式:
preg_match('/'((.*)')$/',$input,$matches);
其他答案都没有有效/准确地回答您的问题:
要获得最快的准确模式,请使用:
$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
重置匹配的起点,(?='))
是积极的前瞻,可确保匹配整个子字符串,而无需包含尾随的右括号。
编辑:抛开所有正则表达式卷积,因为您知道您想要的子字符串被包装在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)]]
做。