Reputation: 51
I written a code to split the following string
(((OPERATING_CARRIER='AB') OR (OPERATING_CARRIER='EY') OR ((OPERATING_CARRIER='VA') AND ((FLIGHT_NO=604) OR ((FLIGHT_NO=603) AND (STOCK='9W'))))))
into following array of strings
OPERATING_CARRIER='AB'
OPERATING_CARRIER='EY'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603
STOCK='9W'
The code is
String sa="(((OPERATING_CARRIER='AB') OR (OPERATING_CARRIER='EY') OR ((OPERATING_CARRIER='VA') AND ((FLIGHT_NO=604) OR ((FLIGHT_NO=603) AND (STOCK='9W'))))))";
Matcher m = Pattern.compile("\\w+\\s*=\\s*(?:'[^']+'|\\d+)").matcher(sa);
//System.out.println("contains "+sa.contains("((("));
Stack<String> in_cond = new Stack<String>();
Iterator<String> iter = in_cond.iterator();
String new_sa=sa;
System.out.println("Indivisual conditions are as follows : ");
while(m.find()) {
String aMatch = m.group();
// add aMatch to match list...
System.out.println(aMatch);
in_cond.push(aMatch);
}
System.out.println("End of Indivisual conditions");
But now in the input string, the "=" can also be "<>" or"<" or ">" or "LIKE" eg :
(((OPERATING_CARRIER<>'AB') OR (OPERATING_CARRIER LIKE'EY') OR ((OPERATING_CARRIER='VA') AND ((FLIGHT_NO<604) OR ((FLIGHT_NO>603) AND (STOCK='9W'))))))
What changes need to be done in the regex?
Upvotes: 1
Views: 54
Reputation: 36304
I guess there are simpler (and more readable) ways to do this :).
Use replaceAll()
to replace all braces with empty String. Next split based on either AND
or OR
.
public static void main(String[] args) {
String s = "(((OPERATING_CARRIER='AB') OR (OPERATING_CARRIER='EY') OR ((OPERATING_CARRIER='VA') AND ((FLIGHT_NO=604) OR ((FLIGHT_NO=603) AND (STOCK='9W'))))))";
String[] arr = s.replaceAll("[()]+","").split("\\s+(OR|AND)\\s+");
for (String str : arr) {
System.out.println(str);
}
}
O/P :
OPERATING_CARRIER='AB'
OPERATING_CARRIER='EY'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603
STOCK='9W'
Upvotes: 3