问题
I'm working on getting all inner parentheses of a string in JavaScript.
For example if I have a string like that (don't bother about % signs, Qx values are surrounded with it)
((!%Q1% || %Q2%) || ((%Q3% && %Q4%) || (%Q5% && %Q6%)))
I would like to get in my result:
(!%Q1% || %Q2%) || ((%Q3% && %Q4%) || (%Q5% && %Q6%))
(!%Q1% || %Q2%)
(%Q3% && %Q4%) || (%Q5% && %Q6%)
(%Q3% && %Q4%)
(%Q5% && %Q6%)
Basically I'm looking for some universal way, not only for example above. I was trying to do so using something like that in loops, but it was working only for much simpler examples (with less parentheses)
init = condition.indexOf('(');
fin = condition.lastIndexOf(')');
inner = condition.substr(init+1,fin-init-1);
I would like to use only JS, but other solutions are welcome.
回答1:
You can use the following code from Sean's comment at Matching Nested Constructs in JavaScript, Part 2 blog, just you will have to add ( and ) at the end of the matches as they will get stripped off:
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/>";
来源:https://stackoverflow.com/questions/34722633/get-all-inner-brackets-parentheses