更新嵌套方括号支持
由于您还需要支持嵌套方括号,并且方括号内的逗号应该被忽略,所以您需要一个简单的解析器来收集您需要的文本块。
public static List<String> splitWithCommaOutsideBrackets(String input) {
int BracketCount = 0;
int start = 0;
List<String> result = new ArrayList<>();
for(int i=0; i<input.length(); i++) {
switch(input.charAt(i)) {
case ',':
if(BracketCount == 0) {
result.add(input.substring(start, i).trim());// Trims the item!
start = i+1;
}
break;
case '[':
BracketCount++;
break;
case ']':
BracketCount--;
if(BracketCount < 0)
return result; // The BracketCount shows the [ and ] number is unbalanced
break;
}
}
if (BracketCount > 0)
return result; // Missing closing ]
result.add(input.substring(start).trim()); // Trims the item!
return result;
}
并将其用作
String s = "ex1 , [ex2 , ex3 ] , [ hh3 , rt5 , w3 [ bn7 ] ] , ex 4 , ex 4, [ex , ex ]";
List<String> res = splitWithCommaOutsideBrackets(s);
for (String t: res) {
System.out.println(t);
}
sample Java code 的输出:
ex1
[ex2 , ex3 ]
[ hh3 , rt5 , w3 [ bn7 ] ]
ex 4
ex 4
[ex , ex ]
请注意,不需要修剪项目。
另外,在我 return result 的地方,您可能想要添加引发异常的代码,而不是像当时那样返回 result。
原答案
在 Java 字符类中,] 和 [ 必须转义,这与 JavaScript 中您只需转义 ] 符号(在字符类内部)不同。
String pat = ",(?![^\\[]*])";
^^
这是IDEONE demo:
String s = "ex1 , [ex2 , ex3 ] , ex 4 , ex 4, [ex , ex ]";
String pat = ",(?![^\\[]*])";
String[] result = s.split(pat);
System.out.println(Arrays.toString(result));
请注意,无论是在 Java 中还是在 JS 中,字符类之外的 ] 都不必转义。