Get all captured groups in Java
Groups aren't thought to find several matches. They are thought to identify several subparts in a single match, e.g. the expression "([A-Za-z]*):([A-Za-z]*)"
would match a key-value pair and you could get the key as group 1 and the value as group 2.
There is only 1 group (= one brackets pair) in your expression and therefore only the groups 0 (always the whole matched expression, independently of your manually defined groups) and 1 (the single group you defined) are returned.
In your case, try calling find
iteratively, if you want more matches.
int i = 0;
while (matcher.find()) {
System.out.println("Match " + i + ": " + matcher.group(1));
i++;
}
JAVA does not offer fancy global option to find all the matches at once. So, you need while loop
here
int i = 0;
while (matcher.find()) {
for (int j = 0; j <= matcher.groupCount(); j++) {
System.out.println("------------------------------------");
System.out.println("Group " + i + ": " + matcher.group(j));
i++;
}
}
Ideone Demo
Also if you know the amount of matches you will get, you can find groups and add them to list then just take values from list when needed to assigned them somewhere else
public static List<String> groupList(String text, Pattern pattern) {
List<String> list = new ArrayList<>();
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
list.add(matcher.group(i));
}
}
return list;