正则表达式匹配完整的单词,但在第一次失败时根本没有匹配

问题描述 投票:2回答:2

我正在寻找一个JS正则表达式匹配完整的单词,但如果有任何不同的单词(任何失败),根本不匹配。

例如:匹配\b(dog|cat)\b


cat dog cat - >一切都很匹配。好。

dog - > dog匹配,即使这里不存在cat。好。

dog cata - > dog匹配,cata没有。我根本不想要任何比赛。

javascript regex
2个回答
0
投票

这是^(?:(?=.*\bdog\b)(?=.*\bcat\b).*|cat|dog)$你想要的吗?

说明:

^                       : beginning of the string
  (?:                   : start non capture group
      (?=.*\bdog\b)     : positive lookahead, zero-length assertion, make sure we have dog somewhere in the string
      (?=.*\bcat\b)     : positive lookahead, zero-length assertion, make sure we have cat somewhere in the string
      .*                : 0 or more any character
    |                   : OR
      cat               : cat alone
    |                   : OR
      dog               : dog alone
  )                     : end group
$                       : end of string

var test = [
    'dog cat',
    'cat dog',
    'dog',
    'cat',
    'dog cata',
    'cat fish',
];
console.log(test.map(function (a) {
  return a + ' ==> ' + a.match(/^(?:(?=.*\bdog\b)(?=.*\bcat\b).*|cat|dog)$/);
}));

0
投票

所以,基本上你想检查你的字符串中的所有单词匹配regexor你的所有字符串都应该来自字符串列表,不是吗?让我们分开所有单词并检查它们是否都属于您的字符串列表。

var reg = /dog|cat|rat/,
    input1 =  "dog   cat      rat",
    input2 = "dog cata   rat",
    input3 = "abcd efgh",
    isMatched = s => !(s.match(/\S+/g) || []).some(e => !(new RegExp(e).test(reg)));
    
console.log(isMatched(input1));
console.log(isMatched(input2));
console.log(isMatched(input3));
© www.soinside.com 2019 - 2024. All rights reserved.