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
768 views
in Technique[技术] by (71.8m points)

regex - Regular expression to match balanced parentheses

I need a regular expression to select all the text between two outer brackets.

Example: some text(text here(possible text)text(possible text(more text)))end text

Result: (text here(possible text)text(possible text(more text)))

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

I want to add this answer for quickreference. Feel free to update.


.NET Regex using balancing groups.

((?>((?<c>)|[^()]+|)(?<-c>))*(?(c)(?!)))

Where c is used as the depth counter.

Demo at Regexstorm.com


PCRE using a recursive pattern.

((?:[^)(]+|(?R))*+)

Demo at regex101; Or without alternation:

((?:[^)(]*(?R)?)*+)

Demo at regex101; Or unrolled for performance:

([^)(]*+(?:(?R)[^)(]*)*+)

Demo at regex101; The pattern is pasted at (?R) which represents (?0).

Perl, PHP, Notepad++, R: perl=TRUE, Python: Regex package with (?V1) for Perl behaviour.


Ruby using subexpression calls.

With Ruby 2.0 g<0> can be used to call full pattern.

((?>[^)(]+|g<0>)*)

Demo at Rubular; Ruby 1.9 only supports capturing group recursion:

(((?>[^)(]+|g<1>)*))

Demo at Rubular  (atomic grouping since Ruby 1.9.3)


JavaScript  API :: XRegExp.matchRecursive

XRegExp.matchRecursive(str, '\(', '\)', 'g');

JS, Java and other regex flavors without recursion up to 2 levels of nesting:

((?:[^)(]+|((?:[^)(]+|([^)(]*))*))*)

Demo at regex101. Deeper nesting needs to be added to pattern.
To fail faster on unbalanced parenthesis drop the + quantifier.


Java: An interesting idea using forward references by @jaytea.


Reference - What does this regex mean?


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

...