我有这样的字符串行:
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
与其拆分,不如尝试使用模式匹配器提取数据。
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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。