Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...