3

For an application I want to parse a String with arithmetic expressions and variables. Just imagine this string:

((A + B) * C) / (D - (E * F))

So I have placeholders here and no actual integer/double values. I am searching for a library which allows me to get the first placeholder, put (via a database query for example) a value into the placeholder and proceed with the next placeholder.

So what I essentially want to do is to allow users to write a string in their domain language without knowing the actual values of the variables. So the application would provide numeric values depending on some "contextual logic" and would output the result of the calculation.

I googled and did not find any suitable library. I found ANTLR, but I think it would be very "heavyweight" for my usecase. Any suggestions?

Dominik Obermaier
  • 5,610
  • 4
  • 34
  • 45
  • 1
    Yes, there is a lightweight ready to use solution: http://jparsec.codehaus.org/ (but it should be fairly trivial to implement your own set of parsing combinators in Java). – SK-logic Oct 20 '11 at 10:57

2 Answers2

2

You are right that ANTLR is a bit of an overkill. However parsing arithmetic expressions in infix notation isn't that hard, see:

Also you should consider using some scripting languages like Groovy or JRuby. Also JDK 6 onwards provides built-in JavaScript support. See my answer here: Creating meta language with Java.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

If all you want to do is simple expressions, and you know the grammar for those expressions in advance, you don't even need a library; you can code this trivially in pure Java.

See this answer for a detailed version of how: Is there an alternative for flex/bison that is usable on 8-bit embedded systems?

If the users are defining thier own expression language, if it is always in the form of a few monadic or binary operators, and they can specify the precedence, you can bend the above answer by parameterizing the parser with a list of operators at several levels of precedence.

If the language can be more sophisticated, you might want to investigate metacompilers.

Community
  • 1
  • 1
Ira Baxter
  • 93,541
  • 22
  • 172
  • 341