有效示例
12[red,green],13[xs,xl,xxl,some other text with chars like _&-@#%]
number[anythingBut ()[]{},anythingBut ()[]{}](,number[anythingBut ()[]{},anythingBut ()[]{}]) or nothing
Full match 12[red,green]
Group 1 12
Group 2 red,green
Full match 13[xs,xl,xxl,some other text with chars like _&-@#%]
Group 1 13
Group 2 xs,xl,xxl,some other text with chars like _&-@#%
无效的示例
13[xs,xl,xxl 9974-?ds12[dfgd,dfgd]]
我尝试的是:(\d+(?=\[))\[([^\(\[\{\}\]\)]+)\]
,regex101 link with what I tried,但这也匹配示例中给出的错误输入。
答案 0 :(得分:0)
如果只需要验证输入,则可以添加一些锚点:
^(?:\d+\[[^\(\[\{\}\]\)]+\](?:,|$))+$
如果还需要获取所有匹配的部分,则可以使用另一个正则表达式。仅使用一个将无法正常工作。
答案 1 :(得分:0)
$in = '12[red,green],13[xs,xl,xxl,some other text with chars like _&-@#%],13[xs,xl,xxl 9974-?ds12[dfgd,dfgd]]';
preg_match_all('/(\d+)\[([^][{}()]+)(?=\](?:,|$))/', $in, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => 12[red,green
[1] => 13[xs,xl,xxl,some other text with chars like _&-@#%
)
[1] => Array
(
[0] => 12
[1] => 13
)
[2] => Array
(
[0] => red,green
[1] => xs,xl,xxl,some other text with chars like _&-@#%
)
)
说明:
/ : regex delimiter
(\d+) : group 1, 1 or more digits
\[ : open square bracket
( : start group 2
[^][{}()]+ : 1 or more any character that is not open or close parenthesis, brackets or square brackets
) : end group 2
(?= : positive lookahead, make sure we have after
\] : a close square bracket
(?:,|$) : non capture group, a comma or end of string
) : end group 2
/ : regex delimiter