获取所有内部 brackets/parentheses

get all inner brackets/parentheses

我正在努力获取 JavaScript 中字符串的所有内括号。

例如,如果我有一个这样的字符串(不要理会 % 符号,Qx 值被它包围)

((!%Q1% || %Q2%) || ((%Q3% && %Q4%) || (%Q5% && %Q6%)))

我想得到我的结果:

(!%Q1% || %Q2%) || ((%Q3% && %Q4%) || (%Q5% && %Q6%))
(!%Q1% || %Q2%) 
(%Q3% && %Q4%) || (%Q5% && %Q6%)
(%Q3% && %Q4%)
(%Q5% && %Q6%)

基本上我正在寻找一些通用的方法,而不仅仅是上面的例子。我试图在循环中使用类似的东西来这样做,但它只适用于更简单的例子(括号较少)

init = condition.indexOf('(');
fin = condition.lastIndexOf(')');
inner = condition.substr(init+1,fin-init-1);

我只想使用 JS,但欢迎使用其他解决方案。

您可以使用 Sean's comment at Matching Nested Constructs in JavaScript, Part 2 blog 中的以下代码,只是您必须在匹配结束时添加 (),因为它们将被剥离:

function matchRecursiveRegExp (str, left, right, flags) {
 var str_copy = str,
 f = flags || "",
 g = f.indexOf("g") > -1,
 x = new RegExp(left + "|" + right, "g" + f.replace(/g/g, "")),
 l = new RegExp(left, f.replace(/g/g, "")),
 a = [],
 b = [],
 keep_going, t, s, m;
 do {
   t = 0;
   keep_going = false;
   while (m = x.exec(str_copy))
   {
     if (l.test(m[0])) {
       if (!t++) {
         s = x.lastIndex;
       } else {
         //another start has occurred, save that off
         b.push(m.index);
       }
     } else if (t) {
        if (!--t) {
          a.push(str_copy.slice(s, m.index));
          //found the end match
          if (!g) return a;
        }
     }
   }
   if (g && b.length) {
   //nested matches found
   //slice the string with the index that was
   //saved and keep going
     str_copy = str_copy.slice(b.shift());
     keep_going = true;
   }
}
 while (keep_going || (t && (x.lastIndex = s)));
 return a;
}

var str = '((!%Q1% || %Q2%) || ((%Q3% && %Q4%) || (%Q5% && %Q6%)))';
var res = matchRecursiveRegExp(str, '\(', '\)', 'g');
for (var i = 0; i<res.length; i++)
  document.body.innerHTML += "(" + res[i] + ")" + "<br/>";