开发者社区> 问答> 正文

regex Java拆分逗号分隔的字符串,但忽略引号,花括号和递归括号内的逗号

我有这样的字符串行:

valueA,{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"},valueB,{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"},valueC,{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"}

我想用逗号分开

上面的字符串应分为:

valueA
{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"}
valueB
{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"}
valueC
{"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3",.....,"propertyn":"valueN"}

尝试一下,但效果不佳。

String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

我怎样才能做到这一点?

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 17:56:28 859 0
1 条回答
写回答
取消 提交回答
  • 与其拆分,不如尝试使用模式匹配器提取数据。

    String line = "valueA,{\"property1\":\"value1\",\"property2\":\"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]\",\"property3\":\"value3\"},valueB,{\"property1\":\"value1\",\"property2\":\"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]\",\"property3\":\"value3\"},valueC,{\"property1\":\"value1\",\"property2\":\"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]\",\"property3\":\"value3\"}";
    Pattern pattern = Pattern.compile("([,]*(value[A-Z])),(\\{\"[\\w\":,\\[\\].]+\"\\})");
    Matcher matcher = pattern.matcher(line);
    List<String> data = new ArrayList<>();
    
    while (matcher.find()) {
        String key = matcher.group(2);
        String value = matcher.group(3);
    
        data.add(key);
        data.add(value);
    
        System.out.println(key);
        System.out.println(value);
    }
    String[] array = data.toArray(new String[0]);
    

    结果输出:

    valueA
    {"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3"}
    valueB
    {"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3"}
    valueC
    {"property1":"value1","property2":"[[[1.5,1.7],[1.9,0.7],.....,[0.5,0.9]]]","property3":"value3"}
    

    回答来源:Stack Overflow

    2020-03-26 17:57:01
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载