Java 中的布尔表达式求值

2022-01-19 00:00:00 boolean expression evaluate java

我正在寻找一种相对更简单(与编写解析器相比)的方法来评估 Java 中的布尔表达式,我不想使用 JEP 库.

我有一个字符串表达式,例如:(x > 4 || x < 8 && p > 6) 我的目标是用值替换变量.p>

有什么方法可以评估这个表达式吗?

请记住,这可以是任何深度,因此编写解析器将非常复杂.

解决方案

您可以使用 Java6 并选择任何流行的脚本语言,例如 Scala、Ruby、Python、Groovy 和 Javascript.您所要做的就是确保您要评估的表达式使用正确的语言.Groovy 可能是最简单的并且集成得最好.

我已经成功地将这种方法用于提供功能的功能,就像流行的电子表格应用程序中的公式/计算列一样.

I'm looking for a relatively simpler (when compared with writing a parser) way to evaluate boolean expressions in Java, and I do not want to use the JEP library.

I have a String expression like: (x > 4 || x < 8 && p > 6) and my aim is to replace the variables with values.

Is there a way by which I can evaluate this expression?

Bear in mind that this can be any level deep so writing a parser would be very complex.

解决方案

You could use the scripting engine in Java6 and the choose any of the popular scripting languages like Scala, Ruby, Python, Groovy, and Javascript. Than all you have to do is make sure the expression you want to evaluate is in the right language. Groovy is probably the easiest and will integrate best.

I have used this method successfully for a feature offering capabilities much like a formula / calculated column in a popular spreadsheet application.

相关文章