正则表达式:匹配除一个单词之外的所有内容

时间:2014-11-03 11:32:29

标签: regex

我正在寻找一个正则表达式模式,它匹配除了一个确切单词之外的所有内容。

例如,决议:

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

我知道您可以排除单个字符列表,但是如何排除完整的字词?

2 个答案:

答案 0 :(得分:2)

使用否定先行断言,

^(?!.*resolutions).*$

OR

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

DEMO

答案 1 :(得分:0)

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