Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match multiple unordered words in a string

I have a list of names and I am looking to filter the list to only return names that contains both the last and first names.

Let's say I am looking for "Joe Doe"

I have the current regex (?:^|\s)Joe|(?:^|\s)Doe

It somewhat works but it is returning all the strings that contains either Joe or Doe. I would like it to match the names that contains both names only, and it could be either "Doe Joe" or "Joe Doe"

like image 936
Newton Avatar asked Mar 23 '23 00:03

Newton


1 Answers

This lookahead based regex should work:

/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/i

Testing:

/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/.test('Joe Doe'); // true
/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/.test('Doe Joe'); // true
like image 159
anubhava Avatar answered Mar 31 '23 20:03

anubhava