Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse complex logical operations in java?

Is there any way to parse strings which include logical and/or operators and get result as true or false in java? For example

    (1 OR 0 AND 1 AND 0 OR(0 AND 0))

I couldn't find any library. Actually I have some ideas but they are so complex. Maybe some easier way?

like image 243
Mrkrky Avatar asked Nov 22 '25 20:11

Mrkrky


1 Answers

You could use already mentioned script engine:

String expression = "(1 || 0 && 1 && 0 ||(0 && 0))";
Object result = new ScriptEngineManager().getEngineByName("JavaScript").eval(expression);
System.out.println(result);

or spring expression language:

String data = "(true OR false AND true AND false OR(false AND false))";
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(data);
result = exp.getValue();
System.out.println(result);

Please note, that in both cases there was needed to modify original expression by replacing eighter lofical operators or logical constants.

like image 184
Daniil Avatar answered Nov 24 '25 10:11

Daniil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!