用正则表达式计算括号 [英] Count parentheses with regular expression
问题描述
我的字符串是:(as(dh(kshd)kj)ad)...()()
如何用正则表达式计算括号?我想选择一个字符串,该字符串从第一个开括号开始,到 ...
How is it possible to count the parentheses with a regular expression? I would like to select the string which begins at the first opening bracket and ends before the ...
将其应用到上面的示例中,这意味着我想获取以下字符串:(as(dh(k(hshd)kj)ad)
Applying that to the above example, that means I would like to get this string: (as(dh(kshd)kj)ad)
我尝试编写它,但这不起作用:
I tried to write it, but this doesn't work:
var str = "(as(dh(kshd)kj)ad)... ()()";
document.write(str.match(/(.*)/m));
推荐答案
正如我在评论中所说,与流行的信念(不要相信人们所说的一切)匹配嵌套括号 可能相反正则表达式.
As I said in the comments, contrary to popular belief (don't believe everything people say) matching nested brackets is possible with regex.
使用它的不利之处在于,您只能将其执行到固定的嵌套级别.对于您希望支持的每个其他级别,您的正则表达式将越来越大.
The downside of using it is that you can only do it up to a fixed level of nesting. And for every additional level you wish to support, your regex will be bigger and bigger.
但是不要相信我.让我演示给你看.正则表达式 \([^()] * \)
匹配一个级别.对于最多两个级别,在此处查看正则表达式.要匹配您的情况,您需要:
But don't take my word for it. Let me show you. The regex \([^()]*\)
matches one level. For up to two levels see the regex here. To match your case, you'd need:
\(([^()]*|\(([^()]*|\([^()]*\))*\))*\)
它将匹配粗体部分: (as(dh(kshd)kj)ad) ...()()
It would match the bold part: (as(dh(kshd)kj)ad)... ()()
检查 此处的演示 ,了解固定嵌套级别的含义.
Check the DEMO HERE and see what I mean by fixed level of nesting.
以此类推.为了继续添加级别,您要做的就是将最后一个 [^()] *
部分更改为([^()] * | \([^()] * \))*
(在此处检查三个级别).正如我所说,它将越来越大.
And so on. To keep adding levels, all you have to do is change the last [^()]*
part to ([^()]*|\([^()]*\))*
(check three levels here). As I said, it will get bigger and bigger.
这篇关于用正则表达式计算括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!