I've written this regex that I need to test against a set of rules in Java. The rules are:
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
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.