java - 使用正则表达式验证密码

标签 java regex string

<分区>

谁能帮我理解为什么这行不通

public boolean validatePassword(String pass){
    final int MIN_LENGTH = 6;// Minimum length 6

    // check if password is correct length and that it does not
    // contain any invalid characters
    if(pass.length() >= MIN_LENGTH && !pass.matches("(.*)[^.-_+!?=a-zA-Z0-9](.*)")){

        // 4 rules, 3 should be fulfilled
        // 1: Contain upper characters (A-Z)
        // 2: Contain lower characters (a-z)
        // 3: Contain numbers (0-9)
        // 4: Contain following character . - _ + ! ? =
        int ruleCount = 0;      // counting fulfilled rules

        if(pass.matches("(.*)[A-Z](.*)")) ruleCount++;
        if(pass.matches("(.*)[a-z](.*)")) ruleCount++;
        if(pass.matches("(.*)[0-9](.*)")) ruleCount++;
        if(pass.matches("(.*)[.-_+!?=](.*)")) ruleCount++;


        if(ruleCount >= 3) return true; // password verified
    }
    // password not verified
    return false;
}

出于某种原因,它接受包含大写字母和小写字母的密码,并且还会验证包含数字和小写字母的密码。但它应该只验证是否满足了 3 个 for 规则。

最佳答案

你打错了最后一张支票。请注意,- 定义了 [] 组中的范围,如 [A-Z]

不要忘记像这里一样使用\\:

if(pass.matches("(.*)[.\\-_+!?=](.*)")) ruleCount++;

关于java - 使用正则表达式验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539686/

相关文章:

java - 从 JDBC 结果集中获取 XML 的最佳方式

python - 如何使用 python 正则表达式避免特殊字符?

python - 仅提取字母和第一位数字

正则表达式 - 结合正向和负向回顾

Java - 逐行将字符串写入文件与单行/无法将字符串转换为字符串[]

c++ - 如何在不向标准 Ubuntu 版本安装额外库的情况下在 C++ 中拆分字符串?

java - 如何检测虚假唤醒

java - hibernate 搜索。如何从索引中排除实体?

java - 使用 ADB 截取屏幕截图并在 java 中检索它而无需写入文件

xcode - Xcode 7 Beta 5 中的 String' 无法转换为 'StringLiteralConvertible'