Regular expression for math operations with parentheses

社会主义新天地 提交于 2019-11-27 16:31:15

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.

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!