0

I am trying to find a php preg_match that can match

test1 test2[...] but not test1 test2 [...]

and return test2(...) as the output as $match.

I tried

preg_match('/^[a-zA-Z0-9][\[](.*)[\]]$/i',"test1 test2[...]", $matches);

But it matches both cases and return the full sentence.

Any help appreciated.

4

1 回答 1

2
preg_match('/([a-zA-Z0-9]+[\[][^\]]+[\]])$/i',"test1 test2[...]", $matches);

注意它说一个或多个字母数字字符+之后[a-zA-Z0-9]

整个表达式周围的(and)将允许您捕捉整个表达式。

由于您的内容在我身边,[]因此我已更改.*为,[^\]]因为正则表达式是贪婪的,以防万一test2[.....] test3[sadsdasdasdad]它会捕获到最后,因为有].

另请注意,由于您使用的是$它最终将始终匹配事物,我不确定这是否是您打算做的。

你可以看看这个以供参考。

于 2009-11-19T01:21:31.627 回答