1

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)";
  • or etc...

and the values of 1, 2, 3, ... are pre-calculated stored in a map like {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.

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.

I need help in writing the evaluate method.

  • 1
    See my SO article on how to write a recursive descent parser, then produces an (expession) tree. It has additional parts that tell you have to evaluate an expression instead of producing the expression tree. https://stackoverflow.com/a/2336769/120163 – Ira Baxter Jan 03 '22 at 20:28
  • `System.out.println(new ScriptEngineManager().getEngineByName("javascript").eval(Pattern.compile("\\d+").matcher(expression.replace("AND", "&&").replace("OR", "||")).replaceAll(m -> String.valueOf(values.get(Integer.parseInt(m.group()))))));` – shmosel Jan 03 '22 at 20:35
  • @shmosel that's a terrible idea. That's how you get remote code execution. Don't use JS for something this simple and also don't do it in one line – Clashsoft Jan 03 '22 at 22:20
  • @Clashsoft I know, I just hate squeezing multiple statements into a one-line comment. – shmosel Jan 03 '22 at 22:41

1 Answers1

0

I covered such problems by embedding Apache Jexl. Otherwise if you want to create your own parser go for Antlr - it likely has a ready to use example for you.

Queeg
  • 7,748
  • 1
  • 16
  • 42