Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture parenthesized groups with java regex

Tags:

java

regex

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?

like image 324
archangle Avatar asked Dec 14 '25 21:12

archangle


1 Answers

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"
like image 171
aioobe Avatar answered Dec 16 '25 13:12

aioobe