简体   繁体   中英

Split a string in java using balanced parantheses

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);
}

Output

OPERATING_CARRIER='AB'
OPERATING_CARRIER='AB'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603

Regex

正则表达式可视化

Here is a way (maybe not the more efficient)

  1. remove brackets
  2. split on OR
  3. split on 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM