tags:

views:

179

answers:

3

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.

+4  A: 

Try look-ahead assertions:

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

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

Gumbo
Emphasis on the "it would be better if...". Regexes suck at ANDs.
John Kugelman
Marking as correct answer, because you were the first to say it's better to do separate searches. Thanks.
Mark A. Nicolosi
+2  A: 

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.

chaos
+1  A: 

Do three separate matches.

The only reason to do it in one, is if you needed it to find them in a specific order.

Brad Gilbert