【问题标题】:Regular expression for password validation in javajava中密码验证的正则表达式
【发布时间】:2018-09-30 06:00:22
【问题描述】:

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

  1. 至少一个大写字符 (A-Z)
  2. 至少一个小写字符 (a-z)
  3. 至少一位数字 (0-9)
  4. 至少一个特殊字符(标点符号)
  5. 密码不应以数字开头
  6. 密码不应以特殊字符结尾

这是我写的正则表达式。 [a-zA-Z\w\D][a-zA-Z0-9\w][a-zA-Z0-9].$

有时有效,有时无效。我不知道为什么!我非常感谢您帮助我解决这个问题。

【问题讨论】:

  • 你最后有.. 匹配任何字符,这违反了 6。在第二对括号后添加 * 以匹配 0 个或更多字符(现在您只匹配 1 个)
  • 提供失败案例的例子会很有帮助。
  • 另外,任何规定密码不能以什么开头或结尾的东西,都不适用于某些密码管理器

标签: java regex passwords


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2011-05-06
      • 2016-10-19
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多