java - 除非分隔符受引号或括号保护,否则如何拆分字符串?

标签 java regex string split

我问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/

相关文章:

java - 使用证书 .cer 连接到 Java 项目中的 Web 服务

java - ResponseBody 方法和普通方法的多个异常处理程序

regex - 两个逗号分隔的字符串之间的 R 匹配

javascript - 正则表达式找到最后一个正文标签

c++ - 字符串标记化,按标记而不是分隔符拆分

java - 在Java中将算术字符串转换为double

c++ - std::string_view 到底比 const std::string& 快多少?

java - 移动<mvc :annotation-driven/>: no declaration can be found for element 'mvc:annotation-driven' 后出错

Java:ECC(纠错码)库?

regex - 用于货币的 Linux sed 正则表达式