As already said, this is not possible with regex. Following is the way
public List<String> readValidJsonStrings(String allText) {
List<String> jsonList = new ArrayList<String>();
int[] endsAt = new int[1];
endsAt[0] = 0;
while(true) {
int startsAt = allText.indexOf("{", endsAt[0]);
if (startsAt == -1) {
break;
}
String aJson = parseJson(allText, startsAt, endsAt);
jsonList.add(aJson);
}
}
private static String parseJson(String str, int startsAt, int[] endsAt) {
Stack<Integer> opStack = new Stack<Integer>();
int i = startsAt + 1;
while (i < str.length()) {
if (str.charAt(i) == '}') {
if (opStack.isEmpty()) {
endsAt[0] = i + 1;
return str.substring(startsAt, i + 1);
} else {
opStack.pop();
}
}else if (str.charAt(i) == '{') {
opStack.push(i);
}
i++;
}
return null;
}
Change "{" to "[", and other fixes.