Gunjan Nigam Gunjan Nigam - 2 months ago 18
Java Question

Java Split string with nested commas

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

Answer

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]