Regular expression for math operations with parentheses

Solution 1:

You can't find matching parentheses with regular expressions. This is a consequence of the pumping lemma for regular languages (the mathematical objects that regexes represent) not holding for languages with matched open/close parens.

You'll need a context-free parser at the least. Those can be built with ANTLR or JavaCC.

Solution 2:

You are not going to be able to accomplish this with a regular expression. An arithmetic expression can be described using a BNF grammar which can be used to generate a parser using a tool like JavaCC or ANTLR.

Here is an expression parser that I implemented using JavaCC:

http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.sapphire/plugins/org.eclipse.sapphire.modeling/src/org/eclipse/sapphire/modeling/el/parser/internal/ExpressionLanguageParser.jj?view=markup&revision=1.6&root=Technology_Project

The source is EPL. If you look around that CVS location, you will also find AST classes and evaluation logic. The implementation is derived from the expression language defined for JSP/JSF specs.