Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex javascript - match multiple search terms ignoring their order

I would like to find all the matches of given strings (divided by spaces) in a string. (The way for example, iTunes search box works).

That, for example, both "ab de" and "de ab" will return true on "abcde" (also "bc e a" or any order should return true)

If I replace the white space with a wild card, "ab*de" would return true on "abcde", but not "de*ab". [I use * and not Regex syntax just for this explanation]

I could not find any pure Regex solution for that. The only solution I could think of is spliting the search term and run multiple Regex.

Is it possible to find a pure Regex expression that will cover all these options ?

like image 569
Ranch Avatar asked Jan 10 '12 18:01

Ranch


People also ask

Does order matter in regex?

The order of the characters inside a character class does not matter. The results are identical. You can use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9.

How do you search for multiple words in a regular expression?

However, to recognize multiple words in any order using regex, I'd suggest the use of quantifier in regex: (\b(james|jack)\b. *){2,} . Unlike lookaround or mode modifier, this works in most regex flavours.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.


2 Answers

Returns true when all parts (divided by , or ' ') of a searchString occur in text. Otherwise false is returned.

filter(text, searchString) {
    const regexStr = '(?=.*' + searchString.split(/\,|\s/).join(')(?=.*') + ')';
    const searchRegEx = new RegExp(regexStr, 'gi');
    return text.match(searchRegEx) !== null;
}
like image 88
Karl Adler Avatar answered Sep 21 '22 06:09

Karl Adler


I'm pretty sure you could come up with a regex to do what you want, but it may not be the most efficient approach.

For example, the regex pattern (?=.*bc)(?=.*e)(?=.*a) will match any string that contains bc, e, and a.

var isMatch = 'abcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals true

var isMatch = 'bcde'.match(/(?=.*bc)(?=.*e)(?=.*a)/) != null; // equals false

You could write a function to dynamically create an expression based on your search terms, but whether it's the best way to accomplish what you are doing is another question.

like image 24
RoccoC5 Avatar answered Sep 19 '22 06:09

RoccoC5