Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - Count parentheses with regular expression

My string is: (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 ...

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(([^()]*|(([^()]*|([^()]*))*))*)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...