Regular expression for Java (validating password)

2

I need a regular expression to validate the following password:

The password must contain at least one element of each :

  • More than 6 characters;
  • Uppercase and lowercase letters;
  • Numbers;
  • Special characters.
  • Currently, I have this:

    if(senha.matches("(^|$)[a-z]+(^|$)[0-9]")) {
        JOptionPane.showMessageDialog(null, senha.matches("(^|$)[a-z]+(^|$)[0-9]"));
    }
    
    else {
        JOptionPane.showMessageDialog(null, senha.matches("(^|$)[a-z]+(^|$)[0-9]"));
    }
    
        
    asked by anonymous 30.09.2017 / 20:33

    1 answer

    3

    Does it have to be regular expression? I ask this because determining that using regular expression is needed seems to me to be a case of XY problem .

    If using regular expressions is not required, you can do this:

    public static boolean senhaForte(String senha) {
        if (senha.length() < 6) return false;
    
        boolean achouNumero = false;
        boolean achouMaiuscula = false;
        boolean achouMinuscula = false;
        boolean achouSimbolo = false;
        for (char c : senha.toCharArray()) {
             if (c >= '0' && c <= '9') {
                 achouNumero = true;
             } else if (c >= 'A' && c <= 'Z') {
                 achouMaiuscula = true;
             } else if (c >= 'a' && c <= 'z') {
                 achouMinuscula = true;
             } else {
                 achouSimbolo = true;
             }
        }
        return achouNumero && achouMaiuscula && achouMinuscula && achouSimbolo;
    }
    

    And this still has the advantage that if you need to change the criteria of what is considered a strong password, it is much easier to tweak it than in a regular expression.

        
    30.09.2017 / 21:02