我想获得数组格式的子字符串,它位于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()
的内部。我使用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)]]'
这种模式匹配所需的字符串(也与启动字≠ '输入':
@^(.+?)\((.+?)\)[email protected]
^(.+?) => 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);
$匹配[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)]]
完成。
@Gamsh我加了一个更简单的方法。看我的编辑。 – mickmackusa