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

时间:2011-06-23 03:52:56

标签: javascript regex string

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

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

'abcd' - >假

'cdef' - >假

'bcd' - >真

修改

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

例如。我想要myregex

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

语句myregex.test('bcd')的评估结果为true

6 个答案:

答案 0 :(得分:94)

这就是你要找的东西:

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

解释如下: Regular expression to match a line that doesn't contain a word?

答案 1 :(得分:16)

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

答案 2 :(得分:5)

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

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

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

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


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