views:

167

answers:

2

How can I use a regular expression to validate the characters in a password? The password must contain at least 1 special character, 1 digit and 1 letter. It should [not] be more than 8 characters long.

+6  A: 

Must you use regular expressions? It seems like the wrong tool for the job.

Instead, I would implement a function that checks for one each of the characters you would like to see, as well as checking the length. The function will be much easier to read than a regular expression that tries to do the same thing.

Greg Hewgill
Plus, the ideal password is irregular.
Jonathan Leffler
+1  A: 

The regex:

^(?=.*\d)(?=.*[a-zA-Z])(?=.*[@#$%^&+=]).*$

will match

  • at least 1 digit,
  • at least 1 letter and
  • at least one special char

Special chars are '@', '#', '$', '%', '^', '&', '+' and '=', the allowed special chars can be changed by changing the third look-ahead group.

However I can't get it to match a max length using regex, which means that Greg is most likely correct and regex is not the way to go for this. The given regex imposes a minimum password length of 3 based on the three matching look-ahead groups. You could enforce a minimum length as Jonathan suggests in his comment by adding an additional look-ahead group: (?=.{8.}) for example gives a minimum length of 8.

beggs