Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
    
if it's an alphanumeric then how come it allows special chars.? – Avinash Raj Mar 25 '15 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. – Zax Mar 25 '15 at 12:02
    
for atleast 8, .{8,} would be enough. – Avinash Raj Mar 25 '15 at 12:03
up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks for the reply. Tried this, this will make sure that the two special characters are appearing continiously – Zax Mar 25 '15 at 12:05
    
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. – Avinash Raj Mar 25 '15 at 12:06
    
there must be 2 special characters, but they might or might not appear continuously one behind another in the input string – Zax Mar 25 '15 at 12:06
    
Perfect!!! I think i had missed ^$.. Its working now. Thanks – Zax Mar 25 '15 at 12:07
    
And also [A-z] matches also the chars other than A-Z and a-z. So that i added [A-Za-z] – Avinash Raj Mar 25 '15 at 12:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.