Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match if all given words are in a string

Tags:

regex

Say I have a query like this: "one two three", if I replace with spaces with | (pipe character) I can match a string if it contains one or more of those words. This is like a logical OR.

Is there something similar that does a logical AND. It should match regardless of word ordering as long as all the words are present in the string.

Unfortunately I'm away from my Mastering Regular Expressions book :(

Edit: I'm using Javascript and the query can contain any amount of words.

like image 866
Mark A. Nicolosi Avatar asked Jul 04 '09 14:07

Mark A. Nicolosi


2 Answers

Try look-ahead assertions:

(?=.*one)(?=.*two)(?=.*three)

But it would be better if you use three separate regular expressions or simpler string searching operations.

like image 142
Gumbo Avatar answered Oct 05 '22 08:10

Gumbo


There's nothing really good for that. You could fairly easily match on three occurrences of any of the words involved:

(?:\b(?:one|two|three)\b.*){3}

but that matches "one one one" as easily as "one two three".

You can use lookahead assertions like Gumbo describes. Or you can write out the permutations, like so:

(?\bone\b.*\btwo\b.*\bthree\b|\btwo\b.*\bone\b.*\bthree\b|\bone\b.*\bthree\b.*\btwo\b|\bthree\b.*\bone\b.*\btwo\b|\bthree\b.*\btwo\b.*\bone\b|\btwo\b.*\bthree\b.*\bone\b)

which is obviously horrible.

Long story short, it's a lot better to do three separate matches.

like image 35
chaos Avatar answered Oct 05 '22 08:10

chaos