I've some string like :
(((a * b) + c) * d)
and want to capture parenthesized groups with java regex. I thought this simple regex
Pattern p = Pattern.compile("\\((.*)\\)",Pattern.DOTALL);
would do the work but it does not.
Whats wrong with that?
The language you're trying to define with your regular expression unfortunately smells non-regular, i.e. regular expressions are not suitable for this type of expressions. (To be precise, "well balanced parenthesis" is not something you can define with regular expressions.)
If you however simply want to find the substring a * b in your example, the following expressions should do:
Pattern p = Pattern.compile("\\(([^()]*)\\)");
Matcher m = p.matcher("(((a * b) * ) + c) * d)");
if (m.find())
System.out.println(m.group(1)); // prints "a * b"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With