Reputation: 61
I need to error check String licenseNumber
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.
Upvotes: 2
Views: 2552
Reputation: 15852
The correct regex will be ^.*[a-zA-Z]{2}[0-9]{7}.*$
String pattern = "^.*[a-zA-Z]{2}[0-9]{7}.*$";
System.out.println( "aa1234567".matches(pattern) ); // true
System.out.println( "aa123456".matches(pattern) ); // false
System.out.println( "aaa12345678".matches(pattern) ); // true
Upvotes: 1
Reputation: 4122
Here's a very straight-forward and rather simple way. This would work for your specific issue (but for any license number that follows the description in your answer)
Well, say you have a string
String str = "ab1234567";
then you can get a char
array:
char[] characters = str.toCharacterArray();
and then check if it is the right length:
boolean isValid = true;
if(characters.length==9){
if((96<characters[0]<123 && 96<characters[1]<123) || (64<characters[0]<91&& 64<characters[1]<91)){//this checks if the first two characters are lowercase letters
for(int i = 2; i< characters.length; i++){
if(!(47<characters[i]<58)){//this checks if the rest are numbers.
isValid = false;
}
}
}else{
isValid = false;
}
}else{
isValid = false;
}
and then if isValid
is true in the end, then your string is a license plate.
Upvotes: -1
Reputation: 12177
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);
...
Upvotes: 2