Regular Expression "AND"

javascript, regex

Solution

Use lookahead. Try this:

if( inputArray.length>1 ) rgx = "(?=.*" + inputArray.join( ")(?=.*" ) + ").*";

You'll end up with something like

(?=.*dog)(?=.*cat)(?=.*mouse).*

Which should only match if all the words appear, but they can be in any order.

- The dog ate the cat who ate the mouse.

- The mouse was eaten by the dog and the cat.

- Most cats love mouses and dogs.

But not

- The dog at the mouse.

- Cats and dogs like mice.

The way it works is that the regex engine scans from the current match point (0) looking for `.*dog`, the first sub-regex (any number of any character, followed by dog). When it determines true-ness of that regex, it resets the match point (back to 0) and continues with the next sub-regex. So, the net is that it doesn't matter where each word is; only that every word is found.

EDIT: @Justin pointed out that i should have a trailing `.*`, which i've added above. Without it, `text.match(regex)` works, but `regex.exec(text)` returns an empty match string. With the trailing `.*`, you get the matching string.

Problem

I'm doing some basic text matching from an input. I need the ability to perform a basic "AND". For "ANY" I split the input by spaces and join each word by the pipe ("|") character but I haven't found a way to tell the regular expression to match any of the words. ``` switch (searchOption) { case "any": inputArray = input.split(" "); if (inputArray.length > 1) { input = inputArray.join("|"); } text = input; break; case "all": inputArray = input.split(" "); ***[WHAT TO DO HERE?]*** text = input; break; case "exact": inputArray = new Array(input); text = input; break; } ``` Seems like it should be easy.

Original source