【问题标题】:verify password using regexes [duplicate]使用正则表达式验证密码 [重复]
【发布时间】:2016-06-03 01:20:06
【问题描述】:

有人可以帮我理解为什么这不起作用

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 规则。

【问题讨论】:

    标签: java regex string


    【解决方案1】:

    你上次检查错了。请注意,- 定义了 [] 组中的范围,例如 [A-Z]

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

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

    【讨论】:

    • 谢谢。这有点欺骗了我。但它现在可以工作了
    【解决方案2】:

    AFIK,matches 是 Pattern 的方法,而不是 String。

    boolean b = Pattern.matches("a.*", text) ;
    

    你应该使用:

    if(Pattern.matches(".*[A-Z].*", pass)) ruleCount++;
    

    其他测试以此类推。

    【讨论】:

    • 感谢您的回答。但没有任何区别。但是通过测试发现,由于某种原因,小写字母和大写字母或数字的模式,它在 "(.*)[.-_+!?=](.*)" 上得到了正匹配,这令人费解对我来说
    • 他们的方法是一样的。 String#matches() 方法在后台调用 Pattern.matches()
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 2016-04-15
    • 2016-04-12
    • 2015-06-10
    • 2016-10-09
    • 2016-10-30
    • 1970-01-01
    相关资源
    最近更新 更多