1

Is there a regex to extract sub strings from a string containing multiple parantheses?

For example my string is

String str = "(A(B(C(D(x)))))";

I want to print all the sub strings that lie within any pair of parantheses :

  A(B(C(D(x))))
  B(C(D(x)))
  C(D(x))
  D(x)
  x

I tried using regex :

        Matcher m = Pattern.compile("\\((.*?)\\)").matcher(str);
        while (m.find()) {
            System.out.println(m.group(1));
        }

But this only extracts the sub string it finds between 1st pair of parentheses.

parul71625
  • 193
  • 2
  • 4
  • 14
  • I don't think it will be possible to solve this in such way because matching balanced parentheses is not possible with regular expressions. Not with standard syntax (as far as I remember .NET has something for balancing). – siarheib Nov 17 '16 at 08:32

1 Answers1

1

I have developed what you requested but not just with regex, but a recursive function. Please check following code:

public static void main(String[] args)
{
    String str = "(A(B(C(D(x)))))";
    findStuff(str);

}

public static void findStuff(String str){
    String pattern = "\\((.+)\\)";

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(str);
    while (m.find())
    {
        String sub = m.group(1);
        System.out.println(" Word: " + sub);

        findStuff(sub);
    }
}
Gokhan Celikkaya
  • 716
  • 1
  • 7
  • 17