Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recursively match a pattern using Regular Expressions?

Tags:

java

regex

The string can be like one of the following:

a(b,c)
a(a(b,c),d)
a(a(a(a(a(b,c),d),a(e,f)),g),h)
etc

I want to match an unlimited number of "a(x,y)". How can I do that using Regex? Here's what I have:

\\w\\(((?:\\([a-zA-Z0-9]+\\))|(?:[a-zA-Z0-9]+)),((?:\\([a-zA-Z0-9]+\\))|(?:[a-zA-Z0-9]+))\\)

It only matches up two recursions of "a(x,y)".

like image 462
Leo Jiang Avatar asked Dec 28 '11 18:12

Leo Jiang


1 Answers

Java's standard regex lib does not support recursion, so you can't match such general nested constructs with it.

But in flavors that do support recursion (Perl, PCRE, .NET, etc) you can use expressions like:

\w+(?:\((?R)(?:,(?R))*\))?
like image 165
Qtax Avatar answered Oct 14 '22 09:10

Qtax