Q:

Java regular expression longest match

I am having a problem with a generic regex that matches (sort of) a typical string of the form
... "field1" "field2" "field3" "field4" ...

What I want to do is, of course, get each of these fields separately. Because the fields can contain any character, I am using a "catch-all" regex of the form
... \"(.*?)\" +\"(.*?)\" +\"(.*?)\" +\"(.*?)\" + ...

The problem is, instead of producing 4 different groups, Java gives me just one, which is merges those 4 above, i.e. I get a single field:
field1" "field2" "field3" "field4

instead of
field1
field2
field3
field4

I have even tried doing things like \"([^\"]*)\" for each of the fields, but the result is the same.
How could I get these 4 fields separately?

A:

Each call to matcher.find() will move to the next match:
String input = "... \"field1\" \"field2\" \"field3\" \"field4\" ...";
Matcher matcher = Pattern.compile("\"(.*?)\"").matcher(input);
while (matcher.find())
    System.out.println(matcher.group(1));

or, if you really want to capture all four in one match:
Matcher matcher = Pattern.compile("\"(.*?)\".*?\"(.*?)\".*?\"(.*?)\".*?\"(.*?)\".*?").matcher(input);
if (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
    System.out.println(matcher.group(4));
}

Both produce the same output, which is:
field1
field2
field3
field4

