1

I need a regular expression to check that if a password contains:

  • [1,6] uppercase/lowercase characters
  • [1,10] digits
  • [0,1] special characters

I tried multiple approach, but without success. I don't know if I can do this verify with regex. The most accurate pattern is : ^(?=(.*[a-zA-Z]){1,6})(?=(.*[0-9]){1,10})(?=(.*[!@#$%^&*()\-__+.]){0,1})

But it don't work good when I have more than 6 char, 10 digits or 1 special character.

Could anyone help me?

0

1 Answer 1

3

I might not use a single regex pattern, but would instead use multiple checks. For example:

String password = "ABC123@";
int numChars = password.replaceAll("(?i)[^A-Z]+", "").length();
int numDigits = password.replaceAll("\\D+", "").length();
int numSpecial = password.replaceAll("[^!@#$%^&*()_+.-]", "").length();

if (numChars >=1 && numChars <= 6 && numDigits >= 1 && numDigits <= 10 &&
    numSpecial <= 1) {
    System.out.println("password is valid");
}
else {
    System.out.println("password is invalid");
}
Sign up to request clarification or add additional context in comments.

5 Comments

And a even more real world solution would be: to rather use "conditions" into a list, and iterate that one by one. So it becomes much easier to change this or that condition later on, or add more.
@GhostCat I guess I should have mentioned that regex is not the best tool for counting characters, leading me to the version above.
@TimBiegeleisen Thank you, which is the best way for validate password in my case (I am not restricted to using just regexp)?
I don't know of a "nice" way to validate your password using a one shot single regex. The above is the best I could conjure up on the time scale of a single Stack Overflow question.
@TimBiegeleisen I was wondering if there is a better option without using regex.

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.