Tommy Barrett Tommy Barrett - 1 year ago 47
Java Question

test to see if string contains 2 letters followed by 7 numbers

I need to error check String

which is supposed to contain 2 letters followed by 7 digits within the String. I'm very new to Java and am in the early stages of classes so all help would be appreciated. I only need to return a true or false.

I'm not sure if there is a way to use loops to check the String or if there is a smarter way.

Answer Source

Use regular expressions:

String pattern = "^[a-zA-Z]{2}[0-9]{7}$";
System.out.println( "aa1234567".matches(pattern) ); // true
System.out.println( "aa123456".matches(pattern) ); // false

boolean verifyLicense = licenseNumber.matches(pattern);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download