Regex to extract data from a String [duplicate]

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)".


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))*\))?

You can also use my Regular Expression library https://github.com/florianingerl/com.florianingerl.util.regex , that supports Recursive Regular Expressions! The API is basically the same as the one of java.util.regex, just the required import statements are different, e.g.

Pattern p = Pattern.compile("(?<first>a\\((?<second>(?'first')|[a-zA-Z]),(?'second')\\))");
assert p.matcher("a(a(a(a(a(b,c),d),a(e,f)),g),h)").find();