marcantonio
marcantonio

Reputation: 1069

Multiple conditions in a Perl regex

This is a pretty specific question regarding Perl regular expressions, I'm hoping it's not out of place.

I have a regex that matches one of several words:

/foo|pizza|chicken/

and one that matches 5 or more words:

(?:\w+ ?){5,}

I need to combine both of these into a single regex (an implementation limitation). It this possible with a single regex?

Thanks in advance!

Upvotes: 1

Views: 2536

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

Yes, you can use a positive lookahead assertion to add a condition:

/^(?=.*\b(?:foo|pizza|chicken)\b)(?:\b\w+\b ?){5,}/

Test it live on regex101.com.

I added word boundary anchors to avoid mismatches on words like food or pizzazz and to make sure \w+ always matches a whole word.

A slightly more efficient alternative uses possessive quantifiers to ensure the same thing:

/^(?=.*\b(?:foo|pizza|chicken)\b)(?:\w++ ?){5,}/

Test it live on regex101.com.

Upvotes: 5

Related Questions