我问How to split a string with conditions 。现在我知道如何忽略两个字符之间的分隔符。
如何检查多组两个字符而不是一个字符?
我发现Regex for splitting a string using space when not surrounded by single or double quotes ,但我不明白在哪里将 ''
更改为 []
。此外,它仅适用于两个组。
是否有一个正则表达式可以使用 ,
进行拆分,但如果它位于 ""
或 []< 之间,则忽略分隔符
还是 {}
?
例如:
// Input
"text1":"text2","text3":"text,4","text,5":["text6","text,7"],"text8":"text9","text10":{"text11":"text,12","text13":"text14","text,15":["text,16","text17"],"text,18":"text19"}
// Output
"text1":"text2"
"text3":"text,4"
"text,5":["text6","text,7"]
"text8":"text9"
"text10":{"text11":"text,12","text13":"text14","text,15":["text,16","text17"],"text,18":"text19"}
最佳答案
您可以使用:
text = "\"text1\":\"text2\",\"text3\":\"text,4\",\"text,5\":[\"text6\",\"text,7\"],\"text8\":\"text9\",\"text10\":{\"text11\":\"text,12\",\"text13\":\"text14\",\"text,15\":[\"text,16\",\"text17\"],\"text,18\":\"text19\"}";
String[] toks = text.split("(?=(?:(?:[^\"]*\"){2})*[^\"]*$)(?![^{]*})(?![^\\[]*\\]),+");
for (String tok: toks)
System.out.printf("%s%n", tok);
-RegEx Demo
输出:
"text1":"text2"
"text3":"text,4"
"text,5":["text6","text,7"]
"text8":"text9"
"text10":{"text11":"text,12","text13":"text14","text,15":["text,16","text17"],"text,18":"text19"}
关于java - 除非分隔符受引号或括号保护,否则如何拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25351421/