简体   繁体   中英

Regex Java optional characters

I have a this regex;

("(?=.*[az]).*") ("(?=.*[0-9]).*") ("(?=.*[AZ]).*") ("(?=.*[!@#$%&*()_+=|<>?{}\\\\[\\\\]~-]).*")

that checks a password with requirements: length =8, then three of the following - a lowerCase, an upperCase, a digit, special character. 3 of the above 4 + length of 8 is required.

What I have works until there is a space in the password, then it prints the wrong message. In other-words, how do I include whitespace in my list of special characters, thanks!

You can try this out:

String password = "pA55w$rd";

int counter = 0;

if(password.length() >= 8)
{
    Pattern pat = Pattern.compile(".*[a-z].*"); // Lowercase
    Matcher m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*[0-9].*"); // Digit
    m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*[A-Z].*"); // Uppercase
    m = pat.matcher(password);
    if(m.find()) counter++;
    pat = Pattern.compile(".*\\W.*"); // Special Character
    m = pat.matcher(password);
    if(m.find()) counter++;

    if(counter == 3 || counter == 4)
    {
        System.out.println("VALID PASSWORD!");
    }
    else
    {
        System.out.println("INVALID PASSWORD!");
    }
}
else
{
    System.out.println("INVALID PASSWORD!");
}

There are two cases: either it matches the length required, or not.

If it does match the length, it checks each of the 4 cases once, and increments a counter every time it does. Since you want it to match 3 or 4 of the cases, I put an if-else case over there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM