Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Match everything but one word [duplicate]

Tags:

regex

I'm looking for a regular expression pattern, that matches everything but one exact word.

For example, resolutions:

monitors/resolutions // Should not match
monitors/34          // Should match
monitors/foobar      // Should match

I know that you can exclude a list of single characters, but how do you exclude a complete word?

like image 334
Johannes Klauß Avatar asked Dec 11 '25 05:12

Johannes Klauß


2 Answers

Use negative lookahead assertion,

^(?!.*resolutions).*$

OR

^(?!.*\bresolutions\b).*$

DEMO

like image 180
Avinash Raj Avatar answered Dec 16 '25 19:12

Avinash Raj


function test(str){
    let match,
        arr = [],
        myRe = /monitors\/((?:(?!resolutions)[\s\S])+)/g;

    while ((match = myRe.exec(str)) != null) {
         arr.push(match[1]);
    } 

  return arr;
}

console.log(test('monitors/resolutions'));
console.log(test('monitors/34'));
console.log(test('monitors/foobar'));

function test(str){
    let match,
        arr = [],
        myRe = /monitors\/(\b(?!resolutions\b).+)/g;

    while ((match = myRe.exec(str)) != null) {
         arr.push(match[1]);
    } 

  return arr;
}

console.log(test('monitors/resolutions'));
console.log(test('monitors/34'));
console.log(test('monitors/foobar'));
like image 31
Юрий Светлов Avatar answered Dec 16 '25 20:12

Юрий Светлов



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!