Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 925
jason Avatar asked Aug 24 '26 05:08

jason


2 Answers

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

Regular expression visualization

like image 167
Stephan Avatar answered Aug 26 '26 22:08

Stephan


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

like image 30
ThomasThiebaud Avatar answered Aug 26 '26 20:08

ThomasThiebaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!