Q:

Plucking JSON IDs out with Java Regex/Matcher API

I have a Java method that will receive a minified JSON string resembling:
{
  "fizz": {
    "_id": "6"
  }
}
{
  "foo": "bar"
}
... (same two above objects repeated but with different values)

Hence minified the string would be {"fizz":{"_id":"6"}}. The string will be different each time the method is called (obviously) but it will adhere to the following format:
"CHUNK" Consists of:
{"<ANYTHING>":{"_id":"<SOME_NUMBER>"}}{<ANY_JSON_OBJECT>}

So as another example the method might receive the following string as input (not minifying it so as to make the example clearer):
{
  "fizz": {
    "_id": "6"
  }
}
{
  "foo": "bar"
}

{
  "swarm": {
    "_id": "18"
  }
}
{
  "whistle": "feather",
  "saywhat": true
}

{
  "beef": {
    "_id": "23"
  }
}
{
  "active": "NO"
}

I need to extract a list of all the _id string values in the given JSON, so in the example above, I'd want to end up with a List<String> containing "6", "18" and "23". My best attempt:
public List<String> extractIds(String json) {
    Pattern pattern = Pattern.compile("\"_id\":.*");
    Matcher matcher = pattern.matcher(json);
    List<String> ids = new ArrayList<>();

    while(matcher.find()) {
      ids.add("???");
    }

    return ids;
}

But I'm not sure whether my regex is jacked up and/or how to use the Matcher API to extract the next extracted ID in the group.
Any ideas where I'm going awry?

A:

You can try this out:
Pattern pattern = Pattern.compile("\"_id\"\\s*:\\s*\"(.*?)\"");
Matcher matcher = pattern.matcher(json);
List<String> ids = new ArrayList<>();

while(matcher.find()) {
    ids.add(matcher.group(1));
}

Explanation -
\"_id\" checks for the preceding "_id" section,
\\s*:\\s* checks for zero or more spaces, a colon :, and zero or more spaces again (I probably could have omitted the spaces part, but I am unfamiliar with JSON, so I didn't know whether there could be multiple spaces or not)
\"(.*?)\" creates group 1 which contains the desired id, enclosed within "" (If you want the double quotes in your array, then use the regex \"_id\"\\s*:\\s*(.*?))
Finally, whenever we find a match for the regex, we add the contents of group 1 to the ArrayList, using matcher.group(1)

