int numA = numMatch.group(1) ;
No. numMatch.group(1)
returns a String
, which can not be assigned to int
.
parseInt
is a static method of Integer
that converts a string of digits into an int
.
Matcher.groupCount()
If your program asks for a group that is not there,
an IndexOutOfBoundsException
is thrown.
For example, in the previous program
int numD = Integer.parseInt( numMatch.group(5) );
would cause such an error. To avoid this, sometimes you need to use
int Matcher.groupCount()
which returns the number of groups in the Pattern.
group(0)
is not counted. For example,
this regular expression has three groups:
([a-z]*)([0-9]*)([A-Z]+)
The example program does not need groupCount()
because the number of groups does not change.
However,
some programs use several patterns as they run
and the number of groups might not always be the same.
(Trick Question:)
What is groupCount()
for
([a-z]*([0-9]*))(X+)