Javascript javascript正则表达式不匹配单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6449131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:46:24  来源:igfitidea点击:

javascript regular expression to not match a word

javascriptregexstring

提问by bxx

How do I use a javascript regular expression to check a string that does not match certain words?

如何使用 javascript 正则表达式检查与某些单词不匹配的字符串?

For example, I want a function that, when passed a string that contains either abcor def, returns false.

例如,我想要一个函数,当传递一个包含abcor的字符串时,它def返回 false。

'abcd' -> false

'abcd' -> 假

'cdef' -> false

'cdef' -> 假

'bcd' -> true

'bcd' -> 真

EDIT

编辑

Preferably, I want a regular expression as simple as something like, [^abc], but it does not deliver the result expected as I need consecutive letters.

最好,我想要一个像 [^abc] 这样简单的正则表达式,但它没有提供预期的结果,因为我需要连续的字母。

eg. I want myregex

例如。我想要myregex

if ( myregex.test('bcd') ) alert('the string does not contain abc or def');

The statement myregex.test('bcd')is evaluated to true.

该语句myregex.test('bcd')被评估为true

回答by ssgao

This is what you are looking for:

这就是你要找的:

^((?!(abc|def)).)*$

the explanation is here: Regular expression to match a line that doesn't contain a word?

解释在这里: 正则表达式匹配不包含单词的行?

回答by Petar Ivanov

if (!s.match(/abc|def/g)) {
    alert("match");
}
else {
    alert("no match");
}

回答by NoBrainer

Here's a clean solution:

这是一个干净的解决方案:

function test(str){
    //Note: should be /(abc)|(def)/i if you want it case insensitive
    var pattern = /(abc)|(def)/;
    return !str.match(pattern);
}

回答by Flimzy

function test(string) {
    return ! string.match(/abc|def/);
}

回答by Bemmu

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

回答by Girish Gupta

This can be done in 2 ways:

这可以通过两种方式完成:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    }