在Java中,如何在不使用括号分隔符的情况下拆分字符串?

In Java, how to split strings without using delimiters in brackets?

我想用逗号分割一个字符串,但我希望括号之间的逗号被忽略。

例如:

Input:
a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6

Output:
a1:b1
a2:b2
[a3:b3-c3, b4, b5]
a4:b6

提前感谢您的帮助。

为了准确起见,您必须逐个字符地解析,否则您可以像这样进行破解:

(伪代码)

1. replace all brackets by (distinct) dummy placeholders (the format will depend on your context)
2. split the (new) string by the (remaining) commas (st.split(","))
3. re-replace the distinct placeholders with the original brackets values (you will have to store them somewhere) (foreach placeholder: st = st.replace(placeholder, bracket);)

注意: 在第 1 步中,您无需手动替换占位符,而是使用正则表达式(例如 /[[^]]+]/)将括号替换为占位符(并将它们存储为好吧),然后在步骤 3 中替换回来。

示例:

输入: a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6

第一步:中间输出: a1:b1, a2:b2, __PLACEHOLDER1_, a4:b6

step2:中间输出:

a1:b1 a2:b2 __PLACEHOLDER1_ a4:b6

第三步:输出: a1:b1 a2:b2 [a3:b3-c3, b4, b5] a4:b6

实际上你在这里做的是分层拆分和替换,因为没有正则表达式可以匹配上下文相关的(因为没有正则表达式可以计算括号)。

您可以使用这个正则表达式 ,(?![^\[]*\]):

String str="a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6";
System.out.println(Arrays.toString(str.split(",(?![^\[]*\])")));

它将忽略方括号内的所有逗号。

Sample program:

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String str="a1:b1, a2:b2, [a3:b3-c3, b4, b5], a4:b6";
        System.out.println(Arrays.toString(str.split(",(?![^\[]*\])")));
     }
}

输出:

[a1:b1,  a2:b2,  [a3:b3-c3, b4, b5],  a4:b6]