简体   繁体   English

Java/Apex 中的动态逻辑表达式解析器/求值

[英]Dynamic logical expression parser/evaluation in Java/Apex

End-user can define condition selections/logical expressions in String like below:最终用户可以在字符串中定义条件选择/逻辑表达式,如下所示:

  • String expression = "((1 OR 2) AND 6 AND (3 OR 4)) AND 5";
  • or String expression = "(1 AND 2 AND 3 AND 4) OR (5 AND 6)";String expression = "(1 AND 2 AND 3 AND 4) OR (5 AND 6)";
  • or etc...或者等等……

and the values of 1, 2, 3, ... are pre-calculated stored in a map like {1: true, 2: false, 3: true, ...}并且 1, 2, 3, ... 的值预先计算并存储在 map 中,例如{1: true, 2: false, 3: true, ...}

The requirement is to evaluate the above expression with the values stored in the map and get the final output in true/false.要求是使用 map 中存储的值评估上述表达式,并以真/假得到最终的 output。

For eg.:例如:

String expression = "(1 AND 2) OR 3";
Map<Integer, Boolean> values = new Map<Integer, Boolean>{1=> true, 2=> false, 3=> true};
System.debug(evaluate(expression, values)); // This should print true

In the above example "(1 AND 2) OR 3" should evaluates to "(true AND false) OR true", which result in final true answer.在上面的例子中,“(1 AND 2)OR 3”应该评估为“(true AND false)OR true”,这会导致最终的真实答案。

I need help in writing the evaluate method.我需要帮助来编写evaluate方法。

I covered such problems by embedding Apache Jexl .我通过嵌入Apache Jexl解决了这些问题。 Otherwise if you want to create your own parser go for Antlr - it likely has a ready to use example for you.否则,如果您想为 Antlr 创建自己的解析器go - 它可能有一个现成的示例供您使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM