代码之家  ›  专栏  ›  技术社区  ›  Ehsan

如何使用正则表达式从括号中提取单词

  •  2
  • Ehsan  · 技术社区  · 7 年前

    这是我的代码:

    var patt = /(?!.+\))\w+/g;
    var str = '( hello ) ehsan (how are) you' ;
    console.log( patt.exec(str) ) ;
    console.log( patt.exec(str) ) ;

    实际结果

    you , null
    

    ehsan , you
    

    有没有一种方法可以通过消极前瞻?

    5 回复  |  直到 7 年前
        1
  •  1
  •   Code Maniac    7 年前

    你可以这样做

    () 然后把它和 space .

    var str = '( hello ) ehsan (how are) you' ;
    
    let op = str.replace(/\(.*?\)/g, '').trim().split(/\s+/)
    console.log(op);
        2
  •  1
  •   The fourth bird    7 年前

    您的正则表达式使用负前瞻 (?!.+\) 断言右边的内容不是右括号。具有上一次出现右括号时的匹配项,因为在此之后,不再有其他匹配项 ) you .

    您可以使用捕获组,而不是使用负前瞻:

    \([^)]+\)\s*(\w+)

    Regex demo

    const regex = /\([^)]+\)\s*(\w+)/g;
    const str = `( hello ) ehsan (how are) you`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
      if (m.index === regex.lastIndex) {
        regex.lastIndex++;
      }
      console.log(m[1]);
    }

    如果发动机支撑 lookbehind 对于无限长量词,还可以使用正向查找:

    (?<=\([^()]+\)) (\w+)

    const regex = /(?<=\([^()]+\))\s*(\w+)/g;
    const str = `( hello ) ehsan (how are) you`;
    
    while ((m = regex.exec(str)) !== null) {
      if (m.index === regex.lastIndex) {
        regex.lastIndex++;
      }
      console.log(m[1]);
    }
        3
  •  1
  •   revo shanwije    7 年前

    var str = '( hello ) ehsan iran (how are) you';
    console.log(
      str.match(/\([^()]*\)|\w+/g).filter(x => x[0] !== '(')
    )

    第二种方法是欺骗消极前瞻:

    var str = '( hello ) ehsan iran (how are) you';
    console.log(
      str.match(/\w+(?![^()]*\))/g)
    )

        4
  •  0
  •   str    7 年前

    解决这个问题的一个简单方法是 split :

    const input = '( hello ) ehsan (how are) you';
    const output = input.split(/\(.+?\)/);
    
    console.log(output);
    console.log(output.filter(v => v));
    console.log(output.filter(v => v).map(v => v.trim()));
        5
  •  0
  •   hygull    7 年前

    下面的语句给出了您期望的输出。

    var patt = /(?!.+\))\w+/g;
    var str = '( hello ) ehsan (how are) you' ;
    
    var arr = str.split(/\([\w\s]*\)/);   // [ '', ' ehsan ', ' you' ]
    var arr = arr.filter((s) => s!== ""); // [ ' ehsan ', ' you' ]
    
    var s = ("" + arr).trim(); 
    console.log(s); // ehsan , you