regex 如何从字符串捕获数组格式的子字符串

pxiryf3j  于 2023-02-25  发布在  其他
关注(0)|答案(4)|浏览(141)

我想获取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)]]'
olqngx59

olqngx591#

这个模式匹配你想要的字符串(也有开始单词≠ 'input':

@^(.+?)\((.+?)\)$@i
    • 一个
^(.+?)   => find any char at start (ungreedy option)
\)       => find one parenthesis 
(.+?)    => find any char (ungreedy option) => your desired match
\)       => find last parenthesis
yks3o0rb

yks3o0rb2#

试试这个:

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
    preg_match('/input\((.*?\]\])\)/',$input,$matches);
    print_r($matches);
  • *$matches [1]**将包含所需的全部结果。希望此操作有效。
vsmadaxz

vsmadaxz3#

你想把它作为一个字符串吗?使用这个简单的正则表达式:

preg_match('/\((.*)\)$/',$input,$matches);
vuktfyat

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()中,最好、最简单的方法是非正则表达式方法...

$input="input([[1,2,nc(2)],[1,2,nc(1)]])";
echo substr($input,6,-1);
// output: [[1,2,nc(2)],[1,2,nc(1)]]

好的。

相关问题