Regex for password policy [closed]

两盒软妹~` 提交于 2019-12-04 06:22:36
(?=.{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).

I would use multiple regexp's to solve this:

9 chars - you can regexp this but .length() >= 9 is much better!

For the character classes you should use one pr class:

[a-z]+
[A-Z]+
[0-9]+
[£$%&{[...]+ //all the possible symbols you want to accept
or perhaps: 
[:punct:]+ // this depends on your programming language..
or like in the suggestion by @david-halter:
[^\w\s]+  // not alphanumeric or spaces
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!