0
votes

I am new to regex.

Basically I need to validate a password in Java for the following requirement:

  1. The password must contain at least six characters.
  2. The password can contain max 20 characters

In order for the password to be valid any 3 of the 4 validation rules below should be met:

  1. uppercase letters of the English alphabet from A to Z;
  2. lowercase letters a to z;
  3. decimal digits (0 to 9);
  4. non-alphanumeric characters (such as!, $, #,%)

For example:

  1. Q145aqa - OK since contains uppercase, lowercase and digit
  2. 145AS$ - OK since contains uppercase, digit and non-alphanumeric characters
  3. 145234$ - Not OK since contain only digit and non-alphanumeric characters and missing one other validation rule

Basically this is my regex at the moment:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{6,20}$

I don't how how to add the condition for non-alphanumeric characters to the expression and how I can get regex to check if any three of the above 4 validation rules are met in order for the password to be a valid one?

2
Using 1 regex for this is not a good idea. Use separate patterns and count how many of them are matched. - Wiktor Stribiżew
The first two can easily be evaluated with String#length, for the others i´d go with @WiktorStribiżew suggestion. (Wheras the single regex expression will get pretty simple by then, just check if it contains an uppercase Letter etc.) - SomeJavaGuy
@WiktorStribiżew Why? - Kenneth K.
@WiktorStribiżew i am agree with you. i have just prepare example for the same - Butani Vijay
@ButaniVijay: You can upvote the comment if you do, no additional action is necessary I believe :) - Wiktor Stribiżew

2 Answers

2
votes

As per @kevin Esche comment you can test first two validation simply using .length() method of String.

In order for the password to be valid any 3 of the 4 validation rules you can use below code.

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int count=0;
        String password="a34A43";

       boolean hasUppercase = !password.equals(password.toLowerCase());
       boolean hasLowercase = !password.equals(password.toUpperCase());

        if(hasUppercase)
            count++;
        if(hasLowercase)
            count++;

        Pattern p1 = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
        Matcher m = p1.matcher(password);
        if(m.find())
            count++;
        Pattern p2 = Pattern.compile("\\d+", Pattern.CASE_INSENSITIVE);
        Matcher m2 = p2.matcher(password);
        if(m2.find())
            count++;

        if(count>=3)
            System.out.println("Valid Password");
        else
            System.out.println("Invalid Password");
    }   
0
votes

This is a valid example:

private final static String PASSWORD_PATTERN = "^[a-zA-Z0-9\\!\\$\\#\\%]{6,20}$";