The simplest solution to my opinion is to process the input string char-by-char:
public static List<String> split(String input) {
int nParens = 0;
int start = 0;
List<String> result = new ArrayList<>();
for(int i=0; i<input.length(); i++) {
switch(input.charAt(i)) {
case ',':
if(nParens == 0) {
result.add(input.substring(start, i));
start = i+1;
}
break;
case '(':
nParens++;
break;
case ')':
nParens--;
if(nParens < 0)
throw new IllegalArgumentException("Unbalanced parenthesis at offset #"+i);
break;
}
}
if(nParens > 0)
throw new IllegalArgumentException("Missing closing parenthesis");
result.add(input.substring(start));
return result;
}
Example:
split("one,two,3,(4,five),six,(seven),(8,9,ten),eleven,(twelve,13,14,fifteen)") ->
[one, two, 3, (4,five), six, (seven), (8,9,ten), eleven, (twelve,13,14,fifteen)]
As a free bonus, this solution also counts nested parentheses if necessary:
split("one,two,3,(4,(five,six),seven),eight") ->
[one, two, 3, (4,(five,six),seven), eight]
Also it checks whether parentheses are balanced (every open parenthesis has the corresponding closing one).