如何从字符串中捕获数组格式的子字符串
How to capture an array-formatted substring from a string
我想获取 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="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('/input\((.*?\]\])\)/',$input,$matches);
print_r($matches);
$matches[1] 将包含您需要的全部结果。希望这有效。
你想要它纯粹是一个字符串吗?使用这个简单的正则表达式:
preg_match('/\((.*)\)$/',$input,$matches);
这个模式匹配你想要的字符串(也有起始词≠‘input’:
@^(.+?)\((.+?)\)$@i
^(.+?) => find any char at start (ungreedy option)
\) => find one parenthesis
(.+?) => find any char (ungreedy option) => your desired match
\) => find last parenthesis
None 个其他答案 efficiently/accurately 回答了您的问题:
要获得最快的准确模式,请使用:
$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)]]
完成。
我想获取 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="input([[1,2,nc(2)],[1,2,nc(1)]])";
preg_match('/input\((.*?\]\])\)/',$input,$matches);
print_r($matches);
$matches[1] 将包含您需要的全部结果。希望这有效。
你想要它纯粹是一个字符串吗?使用这个简单的正则表达式:
preg_match('/\((.*)\)$/',$input,$matches);
这个模式匹配你想要的字符串(也有起始词≠‘input’:
@^(.+?)\((.+?)\)$@i
^(.+?) => find any char at start (ungreedy option)
\) => find one parenthesis
(.+?) => find any char (ungreedy option) => your desired match
\) => find last parenthesis
None 个其他答案 efficiently/accurately 回答了您的问题:
要获得最快的准确模式,请使用:
$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)]]
完成。