如何使用正则表达式使单词脱离括号

时间:2018-12-15 10:34:43

标签: javascript regex

我想使用正则表达式从括号中删除单词。

这是我的代码:

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 个答案:

答案 0 :(得分:1)

您的正则表达式使用负号(?!.+\)来断言右边的不是右括号。从结束括号的最后一次出现开始就具有匹配项,因为在那之后,不再有)。然后,您将匹配将与you匹配的1个以上的单词字符。

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

\([^)]+\)\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]);
}

答案 1 :(得分:1)

您可以这样做

首先删除()之间的所有字符,然后用space分割。

var str = '( hello ) ehsan (how are) you' ;

let op = str.replace(/\(.*?\)/g, '').trim().split(/\s+/)
console.log(op);

答案 2 :(得分:1)

您有两个选择。首先将匹配括号内的所有内容,然后匹配其余所有单词。之后,您可以轻松过滤它们:

allprojects {
  repositories {
    google() //add this line
    jcenter()
    // ...
  }
}

第二种方法是欺骗负面的前瞻:

FirebaseinstanceIdService

第一种方法是可靠的。第二个需要将所有括号配对并正确关闭。

答案 3 :(得分:0)

一种简单的解决方法是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()));

答案 4 :(得分:0)

以下语句提供您期望的输出。

B