javalif
javalif

Reputation: 11

How to split a string when elements in the string can contain the delimiter

I have a string like that:

String s = "{"Player":{"id":"1","name":"PM001"}},{"Player":{"id":"2","name":"PM002"}}"

I want to omit the "," so the result should be :

{"Player":{"id":"1","name":"PM001"}}

{"Player":{"id":"2","name":"PM002"}}

Upvotes: 0

Views: 93

Answers (2)

hurricane
hurricane

Reputation: 6734

JSONArray newArray = new JSONArray(s);
newArray.get(0);
newArray.get(1);

Upvotes: 3

Bohemian
Bohemian

Reputation: 425168

I would just split on a comma surrounded by reversed curly brackets:

String[] parts = s.split("(?<=}),(?=\\{)");

This uses look arounds to assert the presence of, but not consume, the curly brackets.

Upvotes: 1

Related Questions