简体   繁体   English

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

[英]PHP regular expressions: OR statements containing quantifiers

Why does an?|the not work? 为什么an?|the不行吗? I'm using PHP's preg_match(). 我正在使用PHP的preg_match()。

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

I want it to match "the mona lisa is a painting" and "a dog is an animal" . 我希望它与"the mona lisa is a painting""a dog is an animal"相匹配。

It was working fine until I added in the |the to accommodate the first string example. 它工作正常,直到我在|the添加以容纳第一个字符串示例。

Thanks! 谢谢!

The way you wrote it it either matches using 你写它的方式是匹配使用

^an?

or 要么

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

which is obviously not what you want. 这显然不是你想要的。 You have to put it in parantheses the way you did it with is|was : 你必须把它放在parantheses你的方式is|was

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

To prevent a group from being included in the result, use a non-matching group which syntax is (?: ) . 要防止组包含在结果中,请使用语法为(?: ) :)的非匹配组。 So just use it like this: 所以就像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM