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)
OR
AND
And 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
Hi Folks I have used the following code for splitting the string
String input = "name = 'name_1' AND in_stock IN {'in_stock_1','in_stock_2'} AND ( price BETWEEN '01-jan-2015' and '31-may-2015' OR price = 'price_3' )";
String sa =input;
String[] arr = sa.replaceAll("[()]+","").split("\\s*(\\sOR|\\sAND)\\s*");
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}
thanks for all the inputs and help
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.