0

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 (A-Z)
  2. At least one lower case character (a-z)
  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.

user3479956
  • 21
  • 1
  • 5
  • You have `.` at the end. `.` matches any character, which violates 6. Add `*` after the second pair of brackets to match 0 or more characters (now you match only 1) – An0num0us Apr 19 '18 at 16:40
  • It would be helpful to provide example of the failing cases. – Dorian Gray Apr 19 '18 at 16:44
  • Also, anything that dictates what a password cannot start or end with, will not work with some password managers – Ajaypayne Apr 19 '18 at 17:03
  • 1
    Possible duplicate of [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation) – ctwheels Apr 19 '18 at 17:10

2 Answers2

0

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());
xingbin
  • 23,890
  • 7
  • 43
  • 79
0

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

Glim
  • 361
  • 1
  • 10