Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple java recursive descent parsing library with placeholders

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?

like image 980
Dominik Obermaier Avatar asked Sep 03 '26 10:09

Dominik Obermaier


1 Answers

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

  • Operator-precedence parser
  • Shunting-yard algorithm
  • Algorithms for Parsing Arithmetic Expressions

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.

like image 133
Tomasz Nurkiewicz Avatar answered Sep 05 '26 00:09

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!