我需要拆分以下字符串 ((OPERATING_CARRIER =' AB'或OPERATING_CARRIER =' AB' OR(OPERATING_CARRIER =' VA' AND(FLIGHT_NO = 604或FLIGHT_NO = 603))))) 致:
OPERATING_CARRIER='AB'
OPERATING_CARRIER='AB'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603
我尝试过以下代码
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));
}
我得到的是OPERATING_CARRIER =&#39; AB&#39;或OPERATING_CARRIER =&#39; AB&#39;或(OPERATING_CARRIER =&#39; VA&#39; AND(FLIGHT_NO = 604或FLIGHT_NO = 603
答案 0 :(得分:5)
试试这个:
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
答案 1 :(得分:3)
这是一种方式(可能不是更有效)
OR
AND
这是一个实现
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);
}
}
输出
[OPERATING_CARRIER='AB' , OPERATING_CARRIER='AB' , OPERATING_CARRIER='VA' , FLIGHT_NO=604 , FLIGHT_NO=603]
编辑来自@ Stephan答案的Regexp看起来肯定更好
答案 2 :(得分:1)
Hi Folks我使用以下代码分割字符串
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]);
}
感谢所有输入和帮助