Eyzuky Eyzuky - 1 year ago 77
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


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*","");

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

Answer Source

This regex should work:



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

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

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

Try the Java code online

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download