How to parse a string with a custom logical condition?

I have a file that contains many lines of condition lines, and I need to read this file and convert the logical conditions line into actual code. There are several parameters, and each line of the condition checks whether one or more parameters matches the specified value or contains the specified value. For instance:

$parameterA = "value_1" AND ($parameterB CONTAIN "%value_2%" OR $parameterC = "value_3")

"=", "AND" and "OR" have the meanings of "==", "&" and "||". "%" is a wild card.

After converting the code to code, it should look like this:

if (obj.parameterA == "value_1" && (obj.parameterB.contains("value_2") || obj.parameterC == "value_3"))
     return true;
else return false;

where "obj" is an instance of some class.

I searched for other posts here, and it seems that ANTLR might be a good choice. However, I have no experience with this, and I'm not sure how difficult it is to use it with Java. I just want to check if there are other good ideas before diving into all the details of ANTLR. Thank you so much for your help!

+3
source share
2 answers

Actually, I don’t know if the existing library does this, but the classic way of evaluating an expression is to do this in two steps:

You have the expression in the infix notation, so you need to convert it to the prefix notation to remove the brackets and put the statements in front of the operands.

In the second step, you evaluate the expression using a simple recursive algorithm, which, in turn, will also be required to solve the variables.

, .

: , .

jDTO

, .

0

(, ) , ANTLR, , . . . SO .

0

All Articles