I need to split the following string ((OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603)))) to :
OPERATING_CARRIER='AB'
OPERATING_CARRIER='AB'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603
I have tried the following piece of code
String syntax = "(OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603)))";
List < String > matchList = new ArrayList < String > ();
Pattern regex = Pattern.compile("\\(([^)]*)\\)");
Matcher regexMatcher = regex.matcher(syntax);
while (regexMatcher.find())
{
matchList.add(regexMatcher.group(1));
System.out.println(regexMatcher.group(1));
}
I am getting an output of OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603
Try this:
String s="((OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603))))";
Matcher m = Pattern.compile("\\w+\\s*=\\s*(?:'[^']+'|\\d+)").matcher(s);
while(m.find()) {
String aMatch = m.group();
// add aMatch to match list...
System.out.println(aMatch);
}
OPERATING_CARRIER='AB'
OPERATING_CARRIER='AB'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603

Here is a way (maybe not the more efficient)
ORANDAnd here is an implementation
ArrayList<String> results = new ArrayList<>();
String input = "((OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603))))";
String withoutBrakets = input.replaceAll("\\(", "").replaceAll("\\)","");
String[] withoutOr = withoutBrakets.split("OR");
for(String sOr : withoutOr) {
String[] withoutAnd = sOr.split("AND");
for(String sAnd : withoutAnd) {
results.add(sAnd);
}
}
Output
[OPERATING_CARRIER='AB' , OPERATING_CARRIER='AB' , OPERATING_CARRIER='VA' , FLIGHT_NO=604 , FLIGHT_NO=603]
EDIT Regexp from @Stephan's answer looks definitely better
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With