正则表达式:匹配嵌套括号

时间:2020-10-25 00:49:45

标签: 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)
(third group)
(words(more words)

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

能否请您尝试以下使用递归的正则表达式

\(([^()]|(?R))*\)

答案 1 :(得分:0)

也许这可以解决您的问题。 \((?:[^()]|\([^()]+\))+\)

旁注:对此我并不感到骄傲。

答案 2 :(得分:0)

由于这需要在JavaScript中使用,因此我们有两个选择:

a)指定具有固定嵌套深度的模式(在您的情况下,这似乎可行:

\((?:[^()]|\([^()]*\))*\)

const regex = /\((?:[^()]|\([^()]*\))*\)/g;
const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

或使用实现递归匹配的XRegexp(或类似的库):

const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`;
console.log(XRegExp.matchRecursive(str, '\\(', '\\)', 'g'));
<script src="https://cdn.jsdelivr.net/npm/xregexp@4.3.0/xregexp-all.js"></script>