简体   繁体   中英

Validating a string of text to match a per-determinded format in java

I'm attempting to write a validation method that will validate if someone has entered their license number in error, I've searched around and found some ideas but I just cant get the result that I want. The correct format should be TWO letters followed by SEVEN numbers, the two letters and seven numbers could change but the format should remain the same for exmaple:

AB1234567

If the user entered this value then the boolean would be true, if they entered say:

A12345678 or AB12345Y7 or even not matching the correct length such as AB10

it would then return as false, my code that I've attempted is below, any help or push in the right direction is appreciated.

public boolean validateLicense() 
{
    boolean retValue = false;
    if ((this.licenseNumber.matches("[a-zA-Z]{2}\\d{6}")))
        retValue = true;
    return retValue;
}  

The first thing is that you said seven numbers, but in regex, there is d{6}. And the second thing is that if you change that to: [a-zA-Z]{2}\\d{7} it will match that string too: kjasd;lkfjAB1234567jklsdfa. Your regex needs to be: ^[a-zA-Z]{2}\\d{7}$


^ - start of the string $ - end of the string

Code:

public boolean validateLicense() 
{
boolean retValue = false;
if ((this.licenseNumber.matches("^[a-zA-Z]{2}\\d{7}$")))
    retValue = true;
return retValue;
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM