1

I'm writing a regular expression to validate a password. The conditions are:

  1. Password must contain at least two special characters

  2. Password must be at least eight characters long

  3. Password must be alpha numeric

I'm able to make sure that there are atleast 8 characters, atleast one alphabet, atleast one number and atleast one special character using the below Regular expression:

(?=.*[A-z])(?=.*[0-9])(?=.*?[!@#$%\^&*\(\)\-_+=;:'""\/\[\]{},.<>|`]).{8,32}

Only condition i'm not able to get is there must be atleast two special characters (Above Reg exp is atleast one special characters). Does anyone have any idea on this?

Thanks in advance.

3
  • if it's an alphanumeric then how come it allows special chars.? Commented Mar 25, 2015 at 12:00
  • @AvinashRaj: by alphanumberic, i mean there must be both alphabet and numbers. Only issue is how to make sure that there are atleast 2 special characters. Commented Mar 25, 2015 at 12:02
  • for atleast 8, .{8,} would be enough. Commented Mar 25, 2015 at 12:03

1 Answer 1

1

Only condition i'm not able to get is there must be atleast two special characters.

Make it twice by putting the pattern which was present inside the lookahead inside a group and then make it to repeat exactly two times.

^(?=.*[A-Za-z])(?=.*[0-9])(?=(?:.*?[!@#$%\^&*\(\)\-_+=;:'""\/\[\]{},.<>|`]){2}).{8,32}$

If you want to allow atleast 8 characters then you don't need to include 32 inside the range quantifier, just .{8,} would be enough.

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

4 Comments

Thanks for the reply. Tried this, this will make sure that the two special characters are appearing continiously
no, it asserts that the string must contain atleast two special chars. And it won't be continuous. See i make the .*? also to repeat.
there must be 2 special characters, but they might or might not appear continuously one behind another in the input string
And also [A-z] matches also the chars other than A-Z and a-z. So that i added [A-Za-z]

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.