I have the following regex pattern: ^(\d+)(;(\d+))*$. And I would like to get the number of groups in that regex and the value of each.
I tried using groupCount and group but I get the following results:
Input: "1"
Groups: 3
"1", "1", null, null
Input: "1;2"
Groups: 3
"1;2", "1", ";2", "2"
Input: "1;2;3"
Groups: 3
"1;2;3", "1", ";3", "3"
Input: "1;2;3;4"
Groups: 3
"1;2;3;4", "1", ";4", "4"
I was expecting for the first one "1" to get 1 from groupCount. And in the case of the last, "1;2;3;4", I was expecting to get 7 from groupCount.
Is there any method on Matcher that returns what I was expecting?
EDIT: Added the code that generated the above output
String input = "1";
Pattern pattern = Pattern.compile("^(\\d+)(;(\\d+))*$");
for (int i = 2; i < 6; ++i) {
Matcher matcher = pattern.matcher(input);
matcher.matches();
System.out.println("Input: \"" + input + "\"\nGroups: " + matcher.groupCount());
for (int group = 0; group <= matcher.groupCount(); ++group) {
System.out.print("\"" + matcher.group(group) + "\", ");
}
System.out.println();
input += ";" + i;
}
I am sorry, but there is a misunderstanding on your side about groups.
You define the number of groups with your regex. It is not dependent on the string. And in your regex you define 3 groups:
The Groups are numbered by the opening brackets. So you regex will always have exactly 3 groups. If they match something is something completely different.
So, in the first group there will always be the first found number. For the other two groups, you are doing something special: You are repeating a capturing group.
Since the following numbers you are matching are all stored in group 3, you will find only the last one in the final result. In .net you would be able to read out all matches, but I don’t think it is possible in Java.
Solution:
Validate the String with a regex
And if the format is OK, then get the numbers by doing a split on “;”