1

I've just created this class for a password validation

 /* 
 *  ^                         Start anchor
 *  (?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
 *  (?=.*[!@#$&*])            Ensure string has one special case letter.
 *  (?=.*[0-9].*[0-9])        Ensure string has two digits.
 *  (?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
 *  .{8}                      Ensure string is of length 8.
 *  $                         End anchor.
 */
public class PasswordUtils {

    private static final String PWD_REGEX = "^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z])";

    /**
     * Non instantiable.
     */
    private PasswordUtils() {
        throw new AssertionError("Non instantiable");
    }

    public static boolean match (String pwd1, String pwd2) {
        return StringUtils.equals(pwd1, pwd2);
    }

    public static boolean isStrong(String password){
        return password.matches(PWD_REGEX);
     }
}

Then this Junit, but it seems that the pwd does not match the requirements of the regular expression

private final String PWD6 = "Pi89pR&s";

@Test
public void testStrong () {
    assertTrue(PasswordUtils.isStrong(PWD6));
}
1
  • 4
    It's easier not to use regex. Just iterate the string one char at a time, counting the number of upper case, lower case etc. Then ensure the counts meet your criteria. Commented May 7, 2017 at 16:19

2 Answers 2

1

Try this hope this will help you out..

Regex: ^(?=.*?[A-Z].*?[A-Z])(?=.*?[a-z].*?[a-z].*?[a-z])(?=.*?[\d].*?[\d])(?=.*?[^\w]).{8}$

1. ^ start of string.

2. (?=.*?[A-Z].*?[A-Z]) positive look ahead for two uppercase characters.

3. (?=.*?[a-z].*?[a-z].*?[a-z]) positive look ahead for three lowercase characters.

4. (?=.*?[\d].*?[\d]) positive look ahead for two digits.

5. (?=.*?[^\w]) positive look ahead for non-word character

6. .{8} will match exactly 8 characters.

7. $ end of string.

Regex code demo

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=(?:.*[0-9]){2})(?=(?:.*[!@#$&*]){1}).{8}

The basic idea is:

(?=(?:.*[GROUP]){NUMBER})

Where GROUP is the grouping you want to match (i.e A-Z) and NUMBER is how many.

Also note, you can use {NUMBER,} if you want to match NUMBER or more occurrences of each group.

https://regex101.com/r/JGtIkF/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.