Java: regex to find outer square brackets pairs

1.4k views Asked by At

I would like to find the content of all the outer square brackets pairs in a string.

If an outer pair has an inner pair then it should not be matched separately.

For example string: [abc][123][cde[456[aq[]1q1]]] results should be:

  • abc
  • 123
  • cde[456[aq[]1q1]]

Any help will be highly appreciated...

3

There are 3 answers

0
Prabhu R.D On

This works :)

      String[] ans=input.replaceAll("^\\[|\\]$","").replaceAll("\\]\\["," ").replaceAll("  ","\\[\\]\\[\\]").replaceAll("\\[\\] ","\\[\\]\\[\\]").split(" ");
      System.out.println(Arrays.toString(ans));
0
Attila Neparáczki On
 "(^|\])\[(.*)\]($|[)"

using the most outer brackets always have a bracket next to them or end of string or start of string so this is essentially matching "[something]" if it's preceded by ^ or ] and has [ or $ after it.

0
Nilesh On

As already said, this is not possible with regex. Following is the way

public List<String> readValidJsonStrings(String allText) {   
    List<String> jsonList = new ArrayList<String>();
    int[] endsAt = new int[1];
    endsAt[0] = 0;
    while(true) {
        int startsAt = allText.indexOf("{", endsAt[0]);
        if (startsAt == -1) {
            break;
        }
        String aJson = parseJson(allText, startsAt, endsAt);
        jsonList.add(aJson);
    }
}

private static String parseJson(String str, int startsAt, int[] endsAt) {

    Stack<Integer> opStack = new Stack<Integer>();
    int i = startsAt + 1;
    while (i < str.length()) {

        if (str.charAt(i) == '}') {
            if (opStack.isEmpty()) {
                endsAt[0] = i + 1;
                return str.substring(startsAt, i + 1);
            } else {
                opStack.pop();
            }
        }else if (str.charAt(i) == '{') {
            opStack.push(i);
        }

        i++;
    }

    return null;
}

Change "{" to "[", and other fixes.