简体   繁体   中英

Regular expression for validation

I need to verify a password string by using Java. This is the requirement of validation:

  • at least 1 number
  • at least 1 alphabet character
  • at least 1 character from set !@#$%^&*()_+=-~`][{};':"/.>?,<
  • 8 to 20 characters

After screwing around and banging my head to the wall several times, I came up with this regular expression

if (!password.matches("^(?=.+[0-9])(?=.+[a-zA-Z])(?=.+[\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E])[0-9a-zA-Z\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E]{8,20}$")) {

}

which looks too awful and insane. Is there any better way to achieve this mission ?

I recommend using the regular expressions for what they do best, but using code for things that the regexp doesn't do well. Something like this. (Sorry, I haven't tested this code, but it should give the idea even if I made a mistake and it won't run.)

Pattern special_chars = Pattern.compile("[!@#$%^&*()_+=-~`\][{};':\"/.>?,<]");
Pattern number_chars = Pattern.compile("[0-9]");
Pattern letter_chars = Pattern.compile("[a-zA-Z]");

boolean valid;

valid = (special_chars.matcher(password).find() &&
        number_chars.matcher(password).find() &&
        letter_chars.matcher(password).find() &&
        8 <= password.length() && password.length() <= 20);

With guava CharMatcher .

// at least 1 number
CharMatcher.inRange('0', '9').countIn(password) >= 1 && 
// at least 1 alphabet character
CharMatcher.inRange('a', 'z').or(inRange('A', 'Z')).countIn(password) >= 1 && 
// at least 1 character from set !@#$%^&*()_+=-~`][{};':"/.>?,<
CharMatcher.anyOf("!@#$%^&*()_+=-~`][{};':\"/.>?,<").countIn(password) >= 1 && 
// 8 to 20 characters
password.length() >= 8 && password.length() <= 20

this assumes you want latin alphabet

i believe this has already been answered.

Regular Expression for password validation

but may i suggest that you split up the validation into the respective categories? this way it may be easier and you will be able to tell the user exactly what they're missing.

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