Javascript 正则表达式:匹配嵌套括号
考虑以下字符串:Javascript 正则表达式:匹配嵌套括号,javascript,regex,Javascript,Regex,考虑以下字符串: (first group) (second group) (third group)hello example (words(more words) here) something 所需的匹配将是: (first group) (second group) (third group) (words(more words) here) 我尝试构建一个正则表达式,如下所示: /\(.*?\)/g 但它符合以下条件: (first group) (second group) (
(first group) (second group) (third group)hello example (words(more words) here) something
所需的匹配将是:
(first group)
(second group)
(third group)
(words(more words) here)
我尝试构建一个正则表达式,如下所示:
/\(.*?\)/g
但它符合以下条件:
(first group)
(second group)
(third group)
(words(more words)
有什么想法吗?你能试试下面使用递归的正则表达式吗
\(([^()]|(?R))*\)
也许这对你的情况有用<代码>\((?:[^()]\([^()]+\)+\)
旁注:我并不太为自己的做法感到骄傲。因为这需要在JavaScript中使用,所以我们有两种选择: a) 指定具有固定嵌套深度的图案(这在您的情况下似乎有效:
\((?:[^()]|\([^()]*\))*\)
const regex=/\((?:[^()]\([^()]*\)*\)/g;
const str=`(第一组)(第二组)(第三组)hello示例(这里有单词(更多单词))something`;
让m;
while((m=regex.exec(str))!==null){
//这是避免具有零宽度匹配的无限循环所必需的
if(m.index==regex.lastIndex){
regex.lastIndex++;
}
//可以通过'm`-变量访问结果。
m、 forEach((匹配,组索引)=>{
log(`Found match,group${groupIndex}:${match}`);
});
}
无效的正则表达式:无效的组。由于某种原因,转义序列反斜杠未被过帐。请添加like\(([^()]|(?R))*\)。