Jesper
Jesper

Reputation: 23

RegEx - match minimum two words

I would like to see if a string contains minimum two specific words.

eg.: words to look for: good, day, hello

Match: What a good day
No match: What a day
Match: Hello and good day

So there should be at least two words in the string for the match to be..

For now I have: /(good)|(day)|(hallo)/gmi

but that makes a match if just one word is pressent.

Is that possible?

Upvotes: 0

Views: 270

Answers (2)

Hao Wu
Hao Wu

Reputation: 20834

I guess you can brute force all the combinations along with positive lookaheads:

^(?:(?=.*good)(?=.*day)|(?=.*good)(?=.*hello)|(?=.*day)(?=.*hello)).*$

Notice with lookaheads, the order of the word appearance doesn't matter.

Here's how it looks:

Test cases


Edit

Assuming text like good good is not allowed, and inspired by Michał Turczyn's answer it can be simply as:

^.*(good|day|hello).*(?!\1)(?1).*$

Or if you're using non-pcre regex engine such as javascript

^.*(good|day|hello).*(?!\1)(?:good|day|hello).*$

See the results here

Upvotes: 2

Michał Turczyn
Michał Turczyn

Reputation: 37430

You could try ^.*(?:good|day|hello).*(?:good|day|hello).*$

Explanation:

^ - match beginning of a line

.* - match zero or more of any characters,

(?:...) - non-capturing group

good|day|hello - alternation, match one from list,

$ - match end of a line,

Regex demo

Upvotes: 1

Related Questions