go to previous page   go to home page   go to next page
int numA = numMatch.group(1) ;  

Answer:

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.

QUESTION 12:

(Trick Question:) What is groupCount() for ([a-z]*([0-9]*))(X+)