首页 > 解决方案 > 如何使用正则表达式从括号中取出单词

问题描述

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

这是我的代码:

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

有没有办法通过负前瞻?

标签: javascriptregex

解决方案


您的正则表达式使用负前瞻(?!.+\)来断言右侧的内容不是右括号。这与最后一次出现的右括号匹配,因为在那之后,没有更多的)。然后你匹配 1+ 个单词字符,这些字符将匹配you.

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

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

正则表达式演示

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并接受无限长度的量词,您也可以使用正向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]);
}


推荐阅读