3

I've looked on here for some ideas but I still seem to be struggling with coming up with a regular expression to meet my requirements.

I need a regular expression to check a password format, the criteria are:

  • At least 1 uppercase letter
  • At least 1 number
  • Only alphanumeric characters (no special characters)
  • At least 8 characters long

The regular expression I'm using is:

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

However this is also allowing characters like !$&.

Is there a modification I need to make to this to get it to stop these special characters being accepted?

stema
  • 90,351
  • 20
  • 107
  • 135
user1268548
  • 75
  • 1
  • 7

1 Answers1

8

Change the last part .{8,} to [a-zA-Z\d]{8,}

 ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$
Toto
  • 89,455
  • 62
  • 89
  • 125
  • @M42 Why doesn't this: `^(?=.*[\!\#\@\$\%\&\/\(\)\=\?\*\-\+\-\_\.\:\;\,\]\[\{\}])(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$` work if i wanted to allow special chars as well? – Jo Smo Aug 20 '14 at 16:54
  • @tastro: you have to replace the last `[a-zA-Z\d]{8,}` by `.{8,}`. – Toto Aug 20 '14 at 17:00
  • @M42 thank, but it still doesn't work. Could you please explain what ?=.* does? I know that `a?` allows an `a` or no `a` at all. Just don't know what the question mark (?) does when you put an equals (=) behind it. – Jo Smo Aug 20 '14 at 17:53
  • @tastro: The notation `(?=.....)` is a positive look ahead. Have a look at http://www.regular-expressions.info/lookaround.html but this doesn't work in some regex flavour. If you have more questions, it'll be better to ask another question than have a discution in the comment part :-) – Toto Aug 20 '14 at 18:07
  • @M42 done: http://stackoverflow.com/questions/25411819/regex-regular-expression-for-password-validation Thanks again! – Jo Smo Aug 20 '14 at 18:20