user3758346 user3758346 - 1 month ago 7
Java Question

How to separate Boolean expressions on operators (JAVA)?

How to separate Boolean expressions on operators?
I have expressions as the following String:

String expression = “((468551X68X304.NAOK == \"2\") and (468551X68X305.NAOK > \"2\") and (468551X68X308.NAOK != \"2000\" or 468551X68X308.NAOK > \"2000\")) “;


I want to get all the variables in an array, for example:

a[0] = “468551X68X304.NAOK”;
a[1] = “468551X68X305.NAOK”;
a[2] = “468551X68X308.NAOK”;
a[3] = “468551X68X308.NAOK”;


May someone give me an idea to solve it?

Thanks,

Answer

This can be done using a regular expression.

The following regex matches the variables that are formatted like the variables in your boolean expressions:

\d+X\d+X\d+\.NAOK

where every \d+ matches one or more digits.

To extract the variables using this regex, you can use java.util.regex.Pattern and java.util.regex.Matcher like this:

String booleanExpression = "((468551X68X304.NAOK == \"2\") and (468551X68X305.NAOK > \"2\") and (468551X68X308.NAOK != \"2000\" or 468551X68X308.NAOK > \"2000\")) ";
String regex = "\\d+X\\d+X\\d+\\.NAOK"; // Note that backslash pairs don't denote two backslashes here. Because we're representing the regex as a string literal, we have to use escape sequences to represent the backslashes in the regex

Matcher m = Pattern.compile(regex).matcher(booleanExpression);
ArrayList<String> variables = new ArrayList<>();
while(m.find()) // Match a NEW variable (one that wasn't matched in previous iterations
    variables.add(m.group()); // Add the matched variable to the ArrayList