2

I have a nested comma string such as

[1,2,[],[a,b],[ab,bc,cd],[1,2,[3,4],[5,6],7]]

I want to split the string with commas only upto 1st level. The output I am expecting is

1
2
[]
[a,b]
[ab,bc,cd]
[1,2,[3,4],[5,6],7]

I tried splitting string in Java using regexp but couldn't get the correct output. How could we achieve this?

Though this question Java: splitting a comma-separated string but ignoring commas in quotes

is helpful but I have separate start and end nesting tag([,]), so I couldn't directly use that solution

Community
  • 1
  • 1
Gunjan Nigam
  • 1,363
  • 4
  • 10
  • 18
  • 4
    This type of problem is not really suited for regex. I suggest a pure Java solution. – The Guy with The Hat Oct 09 '16 at 03:11
  • 1
    Possible duplicate of [Java: splitting a comma-separated string but ignoring commas in quotes](http://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes) – Tom Oct 09 '16 at 03:13
  • Handling quoted string is different but this is actually handling of nested `[` and `]`. This one needs to be handled in a parser rather than regex. – anubhava Oct 09 '16 at 03:20

1 Answers1

7

Try this.

String s = "[1,2,[],[a,b],[ab,bc,cd],[1,2,[3,4],[5,6],7]]";
StringBuilder sb = new StringBuilder();
int nest = 0;
for (int i = 1; i < s.length() - 1; ++i) {
    char ch = s.charAt(i);
    switch (ch) {
    case ',':
        if (nest == 0) {
            System.out.println(sb);
            sb.setLength(0);
            continue;
        }
        break;
    case '[': ++nest; break;
    case ']': --nest; break;
    }
    sb.append(ch);
}
System.out.println(sb);

result

1
2
[]
[a,b]
[ab,bc,cd]
[1,2,[3,4],[5,6],7]