正则表达式 - 匹配字符串中的多个无序单词

时间:2022-02-21 21:38:38

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"

假设我在寻找“Joe Doe”

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

我有当前的正则表达式(?:^ | \ 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"

它有点工作,但它返回包含Joe或Doe的所有字符串。我希望它匹配仅包含两个名称的名称,它可以是“Doe Joe”或“Joe Doe”

1 个解决方案

#1


7  

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

#1


7  

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