简体   繁体   中英

Need regex for password validation with special characters as optional criteria: java

i need a regex which must match below conditions

Condition 1: Atleast 1 uppercase alphabet
Condition 2: Atleast 1 lowercase alphabet
Condition 3: Atleast 1 digit
Condition 4: Special characters are optional, but if special characters exists in input string, then it must be among these characters: :.;,?!/\\_-()][#"'&$*%+=}{

Below program satisfies Condition 1,Condition 2,Condition 3 but not Condition 4

For Condition 4 this regex checks for atleast 1 special characters, i want this check to be optional.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidation {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String loginpwd = "sssaQjs#d123";
        String LOGIN_PASSWORD_VALIDATION = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\\!\"#$%&()*+,./:;=?\\[\\]_{}])(?=\\S+$).{8,15}";
        Pattern password_Pattern = Pattern.compile(LOGIN_PASSWORD_VALIDATION);
        Matcher password_matcher = password_Pattern.matcher(loginpwd);      

        if(password_matcher.matches())
            System.out.println("match");
        else
            System.out.println("doesnot match");
    }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String password = "sssaQjs#d123";
    boolean hasUppercase = !password.equals(password.toLowerCase());
    boolean hasLowercase = !password.equals(password.toUpperCase());
    boolean hasDigit = password.matches(".*[0-9].*");
    boolean hasSpecial = password.matches(".*<all special characters escaped as alternative>.*");

    if(hasUppercase && hasLowercase && hasDigit && hasSpecial)
        System.out.println("match");
    else
        System.out.println("doesnot match");
}

Adding the three character classes to the character class of special characters would do it as in

String LOGIN_PASSWORD_VALIDATION = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?!.*[^\\\\!\"#$%&()*+,./:;=?\\[\\]_{}A-Za-z0-9])\\S{8,15}";

It asserts that there isn't a character outside the [\\\\\\\\!\\"#$%&()*+,./:;=?\\\\[\\\\]_{}A-Za-z0-9] class. Note the negative look ahead.

Since the character class has letters and digits included, it makes the special characters optional.

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