Pattern quitPattern = Pattern.compile( "(\d)(\d)(\d)" ) ;
A Pattern with capture groups can be used to construct a Matcher.
After the Matcher has done pattern matching,
the characters in each group are available using its group(int number)
method.
Examine the following code:
String response = "123"; // Assume this data came from the user Pattern numPat = Pattern.compile( "(\\d)(\\d)(\\d)" ); Matcher numMatch = numPat.matcher( response ); if ( numMatch.matches() ) { System.out.print ("Digit 1: " + numMatch.group(1) + ", "); System.out.print ("Digit 2: " + numMatch.group(2) + ", " ); System.out.println("Digit 3: " + numMatch.group(3) ); } else System.out.println("No Match." ); }
The program prints:
Digit 1: 1, Digit 2: 2, Digit 3: 3
group(0)
corresponds to the entire pattern that was matched
(in this program, the entire string "123").
group(1)
corresponds to the first capture group
(that matches "1" in this program).
group(2)
corresponds to the first capture group
(that matches "2" in this program), and so on.
null
.matches()
returns false),
then group()
can not be used.What does the following print out?
Pattern numPat = Pattern.compile( "(\\d)(\\w?)(\\d)" ); String response = "79"; Matcher numMatch = numPat.matcher( response ); if ( numMatch.matches() ) { System.out.print ("1:" + numMatch.group(1) + ", "); System.out.print ("2:" + numMatch.group(2) + ", " ); System.out.println("3:" + numMatch.group(3) ); } else System.out.println("No Match." ); }
Notice that the regular expression and the string have been changed.