【问题标题】:Regex: Match everything but one word [duplicate]正则表达式:匹配除一个单词之外的所有内容[重复]
【发布时间】:2014-12-30 01:24:06
【问题描述】:

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

例如,分辨率:

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

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

【问题讨论】:

  • 这是这里最常见的问题之一,提问前请先搜索。

标签: regex


【解决方案1】:

使用否定的前瞻断言,

^(?!.*resolutions).*$

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

DEMO

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多