user993683
user993683

Reputation:

PHP regular expressions: OR statements containing quantifiers

Why does an?|the not work? I'm using PHP's preg_match().

Here's the full regex: "/^an?|the (.+?) (is|was) an? (.+?)$/".

I want it to match "the mona lisa is a painting" and "a dog is an animal".

It was working fine until I added in the |the to accommodate the first string example.

Thanks!

Upvotes: 1

Views: 223

Answers (1)

poke
poke

Reputation: 388073

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:

/^(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? (.+?)$/

Upvotes: 3

Related Questions