[英]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
步骤1:中间输出: a1:b1, a2:b2, __PLACEHOLDER1_, a4:b6
第二步:中间输出:
a1:b1 a2:b2 __PLACEHOLDER1_ a4:b6
步骤3:输出: 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(",(?![^\\[]*\\])")));
它将忽略方括号内的所有逗号。
示例程序 :
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.