Looking for an expression evaluator

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

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?

回答1:

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



回答2:

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:



回答3:

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



回答4:

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



回答5:

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



回答6:

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 variables = new HashMap();   variables.put("City", "New York");   assertEquals("New", evalExpr.eval(variables));


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