I need to get values from a string with a JSON array using regex String example:
[INFO][2022-11-11] Response body :
{
"values":[
"abc123",
"def456",
"xyz789"
]
}
So I want to get the values: abc123, def456, xyz789
Please note I'm working with a string (actually it's a log output) so I'm not sure if I can use any libraries for JSON parsing
I'm trying to use the following regex, but getting only the last array value xyz789:
"values"\s*:\s*\[(\s*"(\w+)"\s*,?)*]
My solution in Java
String pattern = "\"values\"\\s*:\\s*\\[(\\s*\"(\\w+)\"\\s*,?)*]" ;
Matcher matcher = Pattern.compile(pattern).matcher(source());
while (matcher.find()) {
System.out.println("matcher.group() = " + matcher.group());
System.out.println("matcher.group(1) = " + matcher.group(1));
System.out.println("matcher.group(1) = " + matcher.group(2)); //xyz789
}
private static String source() {
String s = "{\"values\": [\n"
+ " \"abc123\", \"def456\", "
+ " \"xyz789\" ]\n"
+ " }";
return s;
}