用于嵌套括号的java regexp
考虑以下java字符串:
String input = "a, b, (c, d), e, f, (g, (h, i))";
你能帮我找一个java regexp来获得它的6个部分:
a b (c,d) e f (g, (h,i))
这是从基于“最外部”逗号的原始输入字符串中获得的。
不要尝试使用正则表达式来执行此类任务,因为Java中的正则表达式不支持递归。 最简单的解决方案是编写自己的解析器,它将计算(
和)
平衡(让我们称之为括号嵌套级别) ,
如果嵌套级别为0
,
则仅拆分。
这个任务的简单代码(也可以在一次迭代中解决这个问题)看起来像
public static List splitOnNotNestedCommas(String data){ List 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; }
用法:
for (String s : splitOnNotNestedCommas("a, b, (c, d), e, f, (g, (h, i))")){ System.out.println(s); }
输出:
a b (c, d) e f (g, (h, i))