Regular expression for password (at least 2 digits and one special character and minimum length 8)

后端 未结 6 1471
情歌与酒
情歌与酒 2020-11-30 06:27

I have been searching for regular expression which accepts at least two digits and one special character and minimum password length is 8. So far I have done the following:

6条回答
  •  再見小時候
    2020-11-30 06:53

    There is no reason, whatsoever, to implement all rules in a single regex. Consider doing it like thus:

    Pattern[] pwdrules = new Pattern[] {
        Pattern.compile("........"),   // at least 8 chars
        Pattern.compile("\d.*\d"),     // 2 digits
        Pattern.compile("[-!"§$%&/()=?+*~#'_:.,;]") // 1 special char
      }
    
    String password = ......;
    boolean passed = true;
    
    for (Pattern p : pwdrules) {
        Matcher m = p.matcher(password);
        if (m.find()) continue;
        System.err.println("Rule " + p + " violated.");
        passed = false;
    }
    
    if (passed) { .. ok case.. }
    else { .. not ok case ... }
    

    This has the added benefit that passwort rules can be added, removed or changed without effort. They can even reside in some ressource file.

    In addition, it is just more readable.

提交回复
热议问题