我想用逗号分割字符串,但我希望忽略括号之间的逗号。
例如:
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
第2步:中间输出:
a1:b1
a2:b2
__占位符1_
a4:b6
第三步:输出:
a1:b1
a2:b2
[a3:b3-c3,b4,b5]
a4:b6
实际上,您在这里所做的是分层拆分和替换,因为没有正则表达式可以匹配上下文相关的内容(因为没有正则表达式可以计算括号)。
关于java - 在Java中,如何在不使用括号中的分隔符的情况下分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29487254/