Consider the following java String:
String input = \"a, b, (c, d), e, f, (g, (h, i))\";
Can you help me to find a java regexp to obtain its 6 p
Don't try to use regex for this kind of task since regex in Java doesn't support recursion. Simplest solution would be writing your own parser which would count balance of (
and )
(lets call it parenthesis nesting level) and will split only on ,
if nesting level would be 0
.
Simple code for this task (which will also solve this problem in one iteration) could look like
public static List<String> splitOnNotNestedCommas(String data){
List<String> resultList = new ArrayList();
StringBuilder sb = new StringBuilder();
int nestingLvl = 0;
for (char ch : data.toCharArray()){
if (ch == '(') nestingLvl++;
if (ch == ')') nestingLvl--;
if (ch == ',' & nestingLvl==0){
resultList.add(sb.toString().trim());
sb.delete(0, sb.length());
}else{
sb.append(ch);
}
}
if (sb.length()>0)
resultList.add(sb.toString().trim());
return resultList;
}
Usage:
for (String s : splitOnNotNestedCommas("a, b, (c, d), e, f, (g, (h, i))")){
System.out.println(s);
}
Output:
a
b
(c, d)
e
f
(g, (h, i))