This is a simple question, but please hear me out - A part of a homework assignment for Java has a password validator method. The requirements are simple - password must be between 6-10 characters, must be made only of digits or letters and has to have at least 2 digits in it to be valid. I made this with if statements and using regex, for some reason I cannot get the non-word character regex to match despite every online regex checker showing this should work and even the jetbrains plugin for regex check shows this should be valid. (I also understand this could be done with a one-liner and none of the if statements but this way is simpler for me.
Example input - MyPass123 should be valid, MyPass123# should match the non-word character and should return "Password must consist only of letters and digits" instead this never happens. I am a beginner in Java so it is most likely I am not doing something right even though it is such a simple problem. Thank you in advance!
Method code below:
public static void passswordCheck(String password)
    {
        if(password.length()<6 || password.length()>10)
        {
            System.out.printf("Password needs to be between 6 and 10 characters");
        }
        else if(password.matches("\\W")) \\This should match when input is MyPass123#
        {
            System.out.printf("Password must consist only of letters and digits");
        }
        else if(!password.matches("/(\\d).*(\\d)/"))
        {
            System.out.printf("Password needs to have at least 2 digits");
        }
        else
        {
            System.out.printf("Password is valid");
        }
    }
                You're only matching if the string consists of a single character which is non alphanumeric (= [^a-zA-Z0-9_]).
If you want any string which contains at least one non alphanumeric character: .*?\W.*
String#matches always performs a whole match, i.e. the match needs to span the whole string from the first to the last character. To search for a match anywhere in the string, you need to use the find method of a Matcher object instead:
final Pattern nonWordChar = Pattern.compile("\\W");
if (nonWordChar.matcher(password).find()) {
    System.out.printf("Password must consist only of letters and digits");
}
…
You will need to do the same with your other regular expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With