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

Let's say I have this query: "one two three" if replaced with spaces | (pipe symbol) I can match a string if it contains one or more of these words. It looks like a logical OR.

Is there something similar that makes logical I. It should match regardless of word order if all words are present in the string.

Unfortunately, I'm not in my book "Mastering Regular Expressions" :(

Edit: I am using Javascript, and the request can contain any number of words.

+4
source share
3 answers

Try confirming:

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

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

+6
source

There is nothing good for this. You could easily match three occurrences of any of the words:

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

but it matches β€œone one” as easily as β€œone two three”.

You can use lookahead statements like the Gumbo description. Or you can write permutations, for example:

 (?\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 terrible.

In short, it is much better to make three separate matches.

+2
source

Make three separate matches.

The only reason to do this in one thing is that you need to find them in a specific order.

+2
source

All Articles