Eyzuky Eyzuky - 5 months ago 16
Java Question

Trying to parse a complex boolean expression in java using regex

I am trying to parse a string that is in the following format:

boolean1 && boolean2 &&..... booleank


or

boolean1 || boolean3 || .... booleank


When || and && can appear between each boolean value (which is in String, i have my own test to see if that string can be a boolean), into this:
String[] array = {boolean1,boolean2,....booleank}
All my data comes in a string and my code (which doesn't work like expected yet) is this:

String line = "a || b && c"; //Just an example to test
String[] booleans = line.split("[||,&&]*");
for(String x: booleans){
x = x.replaceall("\\s*","");
System.out.println(x);
}


This doesn't work as expected..
I want it to print:
a
b
c

Answer

This regex should work:

\s*(&&|\|\|)\s*

Usage:

String line = "a || b && c"; //Just an example to test
String[] booleans = line.split("\\s*(&&|\\|\\|)\\s*");
for(String x: booleans) {
    System.out.println(x);
}

It will also remove the whitespaces, so the line below should not be needed:

x = x.replaceall("\\s*", "");

Try the Java code online