简体   繁体   中英

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?

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

'abcd' -> false

'cdef' -> false

'bcd' -> true

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.

eg. I want myregex

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

The statement myregex.test('bcd') is evaluated to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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