java中密码验证的正则表达式

时间:2018-04-19 16:33:34

标签: java regex passwords

我已经编写了这个正则表达式,我需要针对Java中的一组规则进行测试。规则是:

  1. 至少一个大写字母(A-Z)
  2. 至少一个小写字符(a-z)
  3. 至少一位数字(0-9)
  4. 至少一个特殊字符(标点符号)
  5. 密码不应以数字开头
  6. 密码不应以特殊字符结尾
  7. 这是我写过的正则表达式。 [a-zA-Z\w\D][a-zA-Z0-9\w][a-zA-Z0-9].$

    它有时会起作用,有时它并不起作用。我无法弄清楚原因!我非常感谢你帮助我做到这一点。

2 个答案:

答案 0 :(得分:0)

试试这个:

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());

答案 1 :(得分:0)

试试这个:

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

说明:

^                 # 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

此模式可以轻松添加或删除规则。

这个答案的功劳归于以下两个主题:

Regexp Java for password validation

Regex not beginning with number