简体   繁体   中英

Regular expression for password validation in java

I've written this regex that I need to test against a set of rules in Java. The rules are:

  1. At least one upper case character (AZ)
  2. At least one lower case character (az)
  3. At least one digit (0-9)
  4. At least one special character (Punctuation)
  5. Password should not start with a digit
  6. Password should not end with a special character

This is the regex that I've written. [a-zA-Z\\w\\D][a-zA-Z0-9\\w][a-zA-Z0-9].$

It sometimes works, and sometimes it doesn't. And I can't figure out why! I would really appreciate your help in getting this right.

Try this:

Pattern pattern = Pattern.compile(
        "(?=.*[A-Z])" +  //At least one upper case character (A-Z)
                "(?=.*[a-z])" +     //At least one lower case character (a-z)
                "(?=.*\\d)" +   //At least one digit (0-9)
                "(?=.*\\p{Punct})" +  //At least one special character (Punctuation)
                "^[^\\d]" + // Password should not start with a digit
                ".*" +
                "[a-zA-Z\\d]$");   // Password should not end with a special character
Matcher matcher = pattern.matcher("1Sz1");
System.out.println(matcher.matches());

Try this one:

^[a-zA-Z@#$%^&+=](?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{8,}[a-zA-Z0-9]$

Explanation:

^                 # start-of-string
[a-zA-Z@#$%^&+=]  # first digit letter or special character
(?=.*[0-9])       # a digit must occur at least once
(?=.*[a-z])       # a lower case letter must occur at least once
(?=.*[A-Z])       # an upper case letter must occur at least once
(?=.*[@#$%^&+=])  # a special character must occur at least once
.{8,}             # anything, at least eight places though
[a-zA-Z0-9]       # last digit letter or number
$                 # end-of-string

This patterns makes it easy to add or remove rules.

Credits for this answer goes to these two topics:

Regexp Java for password validation

and

Regex not beginning with number

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