Regular expression for math operations with parent

2019-01-12 13:27发布

问题:

In java, I'm trying to write a regular expression that will match a unit within a mathematical expression, i.e. things that are between operators

What I mean is, in an expression like 1 + [1 + 2], the regex should match the first 1 and then the [1 + 2].

What I have is *[([-+]?\d+(\.\d+)?)(\[.+\])] *

Of which ([-+]?\d+(\.\d+)?) is supposed to match any number and

(\[.+\])

Is supposed to match something inside parentheses, but it isn't working...it's matching things like ']' and ' ' for some reason.

Any help would be great :)

Unfortunately this is part of an exercise and so I can only use the basic java library...It's also meant to be an exercise in regular expressions. Am I missing something basic here?

回答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.



回答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.



回答3:

I'd echo what the other answerers have stated (regex's won't suffice for parsing arithmetic expressions), but recommend parboiled over ANTLR.

They even have a set of calculator examples you could start with.



回答4:

i released an expression evaluator based on Dijkstra's Shunting Yard algorithm, under the terms of the Apache License 2.0:

http://projects.congrace.de/exp4j/index.html