简体   繁体   English

javascript正则表达式不匹配单词

[英]javascript regular expression to not match a word

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 abc or def , returns false.例如,我想要一个函数,当传递包含abcdef的字符串时,返回 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

This is what you are looking for:这就是你要找的:

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

The ?! ?! part is called a negative lookahead assertion .部分称为否定前瞻断言 It means "not followed by".它的意思是“不跟随”。

The explanation is here: Regular expression to match a line that doesn't contain a word解释在这里: 正则表达式匹配不包含单词的行

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

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);
}
function test(string) {
    return ! string.match(/abc|def/);
}

This can be done in 2 ways:这可以通过两种方式完成:

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM