如何使用逗号分割字符串但在某些情况下忽略?

时间:2018-12-04 07:39:40

标签: java java-8

我想在字符串下分割

{"address":"XXXXXX","amount":"0.25"},{"address":"AAAAAA","amount":"0.25"}

分为两个值

{"address":"XXXXXX","amount":"0.25"}
{"address":"AAAAAA","amount":"0.25"}

1 个答案:

答案 0 :(得分:3)

不建议您按照自己的方式解析json,但是如果您确实想拆分,则可以使用正则表达式使用环视方法来解析。这是相同的Java代码。

public static void main(String args[]) throws Exception {
    String s = "{\"address\":\"XXXXXX\",\"amount\":\"0.25\"},{\"address\":\"AAAAAA\",\"amount\":\"0.25\"}";
    String[] data = s.split("(?<=\\}),(?=\\{)");
    Arrays.asList(data).forEach(System.out::println);
}

打印

{"address":"XXXXXX","amount":"0.25"}
{"address":"AAAAAA","amount":"0.25"}