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." ); }
1:7, 2:, 3:9
Group 2 successfully matched the empty string ( the string that contains no characters ), so no characters were printed between 2: and the following comma.
Here is a (somewhat lame) game, that asks the user to enter a three-digit number where the digits add up to a randomly selected sum. For example, if the sum is 23, the number could be 995. Appropriate messages are written if the user is wrong or does not enter a three digit number.
import java.util.regex.*; import java.util.*; public class ThreeDigitSumGame { public static void main(String[] args) { Random rand = new Random(); int target = rand.nextInt( 28 ); System.out.print("Enter a three-digit number "); System.out.print("where the digits add up to " + target + ": " ); Scanner scan = new Scanner( System.in ); String response = scan.nextLine(); Pattern numPat = Pattern.compile( "(\\d)(\\d)(\\d)" ); Matcher numMatch = numPat.matcher( response ); if ( numMatch.matches() ) { int numA = Integer.parseInt( numMatch.group(1) ); int numB = Integer.parseInt( numMatch.group(2) ); int numC = Integer.parseInt( numMatch.group(3) ); if ( numA+numB+numC == target ) System.out.println("Correct!" ); else System.out.println("wrong" ); } else System.out.println("You did not enter a three-digit number." ); } }
Would
int numA = numMatch.group(1) ;
work correctly in this program?