Regular expression for mathematical operations with parentheses

In java, I am trying to write a regular expression that will correspond to a unit in a mathematical expression, i.e. things that are between the operators

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

I have * [([- +]? \ D + (\. \ D +)?) (\ [. + \])] *

Of which ([- +]? \ D + (\. \ D +)?) Is supposed to correspond to any number and

(\ [+. \])

It is supposed to combine something in parentheses, but it doesnโ€™t work ... for some reason it matches things like "]" and "".

Any help would be great :)

Unfortunately, this is part of the exercise, so I can only use the java base library ... It was also intended for regular expression exercises. Am I missing something here?

0
source share
4 answers

You cannot find matching parentheses with regular expressions. This is a consequence of the pumping lemma for regular languages (mathematical objects that are regular expressions) that are not stored for languages โ€‹โ€‹with corresponding pairs of open / closed characters.

At least you need a context-free parser. They can be created using ANTLR or JavaCC.

+2
source

You cannot do this with a regular expression. An arithmetic expression can be described using BNF grammar, which can be used to generate a parser using a tool such as 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

Source - EPL. If you look around this CVS location, you will also find AST classes and evaluation logic. The implementation is derived from an expression language defined for the JSP / JSF specifications.

+1
source

I would repeat what other respondents said (regular expression is not enough to analyze arithmetic expressions), but recommend parboiled for ANTLR.

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

0
source

i released an expression evaluator based on the Dijkstra Shunting Yard algorithm in accordance with the terms of Apache License 2.0 :

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

0
source

Source: https://habr.com/ru/post/904084/


All Articles