I have following Java code:
String s2 = "SUM 12 32 42";
Pattern pat1 = Pattern.compile("(PROD)|(SUM)(\\s+(\\d+))+");
Matcher m = pat1.matcher(s2);
System.out.println(m.matches());
System.out.println(m.groupCount());
for (int i = 1; i <= m.groupCount(); ++i) {
System.out.println(m.group(i));
}
which produces:
true
4
null
SUM
42
42
I wonder what’s a null and why 12 and 32 are missing (I expected to find them amongst groups).
Group
Xfrom this part of your regex:will first match
12, then32and finally42. Each timeX‘s value gets changed, and replaces the previous one. If you want all values, you’ll need aPattern&Matcher.find()approach:which will print:
Matched : SUM : 12 : 32 : 42 Matched : PROD : 1 : 2And you see a
nullprinted because in group 1, there’sPROD, which you didn’t match.