我正在寻找一个JS正则表达式匹配完整的单词,但如果有任何不同的单词(任何失败),根本不匹配。
例如:匹配\b(dog|cat)\b
cat dog cat
- >一切都很匹配。好。
dog
- > dog
匹配,即使这里不存在cat
。好。
dog cata
- > dog
匹配,cata
没有。我根本不想要任何比赛。
这是^(?:(?=.*\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)$/);
}));
所以,基本上你想检查你的字符串中的所有单词匹配regex
or你的所有字符串都应该来自字符串列表,不是吗?让我们分开所有单词并检查它们是否都属于您的字符串列表。
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));