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
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.