Home > Back-end >  Extract data inside parenthesis except being enclosed by semicolon
Extract data inside parenthesis except being enclosed by semicolon

Time:03-22

Want to extract data inside parenthesis. But if those parenthesis are inside any semicolon. Then it should be neglected. Using regular expression.

Input:

XCA(AA BB)AA(AD'(CC)')

Expected Output:

AA BB
AD'(CC)'

CodePudding user response:

\(
    (
        (
            [^\(\)] |
            '\(|
            \)'
        ) 
    )
\)

It consists of three main parts.

  1. [^\(\)] Anything that is not an parenthesis
  2. ' \( an escaped open parenthesis '(
  3. \)' an escaped closing parenthesis )'

All enclosed in a matching parenthesis literals then an outer group (group 1) without repetition and an inner group with repetition.

The matches in group 1 are

AA BB
AD'(CC)'

CodePudding user response:

String in="XCA(AA BB)AA(CC)AD'(CC)'XCA(AA BB)";
        String result="";
        boolean x=false;
        for (int i = 0; i < in.length(); i  ){
        char ch = in.charAt(i);
        String part = String.valueOf(ch);
        int number = 0;
        if (ch == '\'' ) {
            part = "";
            number  ;
            for (int j = i   1; j < in.length(); j  ) {
                char d = in.charAt(j);
                if (d == '\'') {
                    number  ;
                }
                if (d == '\'') {
                    number--;
                    i = j;
                    if (number == 0) {
                        break;
                    }
                }
                part  = d;
            }

        }
        if (ch == '(' ) {
            part = "";
            number  ;
            for (int j = i   1; j < in.length(); j  ) {
                char d = in.charAt(j);
                if (d == '(') {
                    number  ;
                }
                if (d == ')') {
                    number--;
                    i = j;
                    if (number == 0) {
                        break;
                    }
                }
                part  = d;
            }

            System.out.println(part);
        }

        result  = part;
    }
  • Related