3

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?

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122

2 Answers2

5

Use negative lookahead assertion,

^(?!.*resolutions).*$

OR

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

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'));