your programing

단어와 일치하지 않는 자바 스크립트 정규식

lovepro 2020. 10. 5. 20:32
반응형

단어와 일치하지 않는 자바 스크립트 정규식


특정 단어와 일치하지 않는 문자열을 확인하기 위해 자바 스크립트 정규식을 어떻게 사용합니까?

예를 들어, 나도 포함 된 문자열을 전달하면 해당 함수 원하는 abc또는 deffalse를 반환합니다.

'abcd'-> 거짓

'cdef'-> 거짓

'bcd'-> 참

편집하다

가급적이면 [^ abc]와 같이 간단한 정규식을 원하지만 연속 된 문자가 필요하므로 예상 한 결과를 제공하지 않습니다.

예. 내가 원하는myregex

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

myregex.test('bcd')은로 평가됩니다 true.


이것은 당신이 찾고있는 것입니다 :

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

설명은 다음과 같습니다. 단어가 포함되지 않은 줄과 일치하는 정규식?


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

다음은 깨끗한 솔루션입니다.

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/);
}

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

이는 두 가지 방법으로 수행 할 수 있습니다.

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


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

참고 URL : https://stackoverflow.com/questions/6449131/javascript-regular-expression-to-not-match-a-word

반응형