PHP 正则表达式:包含量词的 OR 语句


PHP regular expressions: OR statements containing quantifiers

为什么an?|the不起作用?我正在使用PHP的preg_match()。

这是完整的正则表达式:"/^an?|the (.+?) (is|was) an? (.+?)$/" .

我希望它与"the mona lisa is a painting""a dog is an animal"相匹配。

它工作正常,直到我添加|the以适应第一个字符串示例。

谢谢!

你写它的方式要么匹配

^an?

the (.+?) (is|was) an? (.+?)$

这显然不是你想要的。你必须把它放在一个段落中,就像你用is|was做的那样:

/^(an?|the) (.+?) (is|was) an? (.+?)$/

要防止组包含在结果中,请使用语法(?: )不匹配的组。所以就这样使用它:

/^(?:an?|the) (.+?) (is|was) an? (.+?)$/