Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for an expression evaluator

Tags:

java

I'm looking for an evaluator for simple condition expressions. Expressions should include variables (read only), strings, numbers and some basic operators.

E.g. expressions something like this:

${a} == "Peter" && ( ${b} == null || ${c} > 10 )

So far i implemented a rather "magical" parser that returns an AST that i can evaluate, but i can't believe that i'm the first one to solve that problem.

What existing code could i use instead?

like image 520
Stroboskop Avatar asked Oct 24 '10 21:10

Stroboskop


6 Answers

Have you looked at MVEL? They provide a getting started guide and performance analysis.

Here's one of their simple examples:

// The compiled expression is serializable and can be cached for re-use.
CompiledExpression compiled = MVEL.compileExpression("x * y"); 

Map vars = new HashMap();
vars.put("x", new Integer(5));
vars.put("y", new Integer(10));

// Executes the compiled expression
Integer result = (Integer) MVEL.executeExpression(compiled, vars); 
assert result.intValue() == 50; 

Also (answering my own question) MVEL seems to provide some support for bytecode generation.

Other alternatives, culling from the above answers and my own:

  • Java Expression Parser (JEP) -- and note there is an old version available for free
  • Apache Commons JEXL
  • With regard to Rhino, here's a dude who did some arithmetic evaluation in that context (looks messy)
like image 175
andersoj Avatar answered Oct 14 '22 04:10

andersoj


Sounds like JEXL might work well for you. Check out its syntax reference.

like image 21
Mike Daniels Avatar answered Oct 14 '22 03:10

Mike Daniels


What about SPEL (Spring Expression Lang); http://static.springsource.org/spring/docs/3.0.x/reference/expressions.html

like image 25
NightWolf Avatar answered Oct 14 '22 03:10

NightWolf


Why don't you use Rhino? It's a JavaScript engine already present inside the JDK.

It can evaluate whatever you like to write in JS.. take a look here

like image 40
Jack Avatar answered Oct 14 '22 02:10

Jack


This simple recursive descent parser evaluates constants as named functions having no parameters.

like image 3
trashgod Avatar answered Oct 14 '22 02:10

trashgod


A very simple and easy to use alternative with a lot of built in excel functions for string, date and number formatting.

The library also allows easy addition of custom functions. A lot of examples available on the git page. A simple example using variables

  ExpressionsEvaluator evalExpr = ExpressionsFactory.create("LEFT(City, 3)");
  Map<String, Object> variables = new HashMap<String, Object>();
  variables.put("City", "New York");
  assertEquals("New", evalExpr.eval(variables));
like image 2
Scorpion Avatar answered Oct 14 '22 03:10

Scorpion