I need to enforce the following password policy :
at least 9 characters, with at least one character from each of the 4 character classes (alphabetic lower and upper case; numeric, symbols).
Any regex experts can help out here ? (I am using a Java regex engine)
While we're at it, is there any online tool that can generate a regex for these kind of tasks ?
Thanks !
(?=.{9,})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*
Note that this pattern doesn't include special utf chars like ö
. I would not do this in one regex. I would split it and search for each thing, if you want to validate it.
Here's how I would do it (using positive lookahead):
(?=.{9,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\p{Punct}).*
Full example and test:
// Regexp Description
Pattern p = Pattern.compile("(?=.{9,})" + // "" followed by 9+ symbols
"(?=.*[a-z])" + // --- ' ' --- at least 1 lower
"(?=.*[A-Z])" + // --- ' ' --- at least 1 upper
"(?=.*[0-9])" + // --- ' ' --- at least 1 digit
"(?=.*\\p{Punct})"+ // --- ' ' --- at least 1 symbol
".*"); // the actual characters
String[] tests = {
"aB99", // too short
"abcdefghijk", // missing A
"abcdefGHIJK", // missing 5
"12345678910", // missing a
"abcDEF12345", // missing punct
"abcDEF-2345" // works!
};
for (String s : tests) {
boolean matches = p.matcher(s).matches();
System.out.printf("%-12s: %b%n", s, matches);
}
Output:
aB99 : false
abcdefghijk : false
abcdefGHIJK : false
12345678910 : false
abcDEF12345 : false
abcDEF-2345 : true
Final remark: The problem with this approach is that it's not very user friendly. If you are to give a sensible response to a user, such as "The password is missing a digit-symbol" you need to do the work again (to figure out which requirement failed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With