2

I am to write a regex for following requirements

  1. At least one character
  2. At least one digit
  3. Length must be of 8
  4. At least one special character(Can be any special character)

First three are easy but couldn't find a way to restrict for at least special character(any possible special char like ',":*^%>? etc).

Joey
  • 344,408
  • 85
  • 689
  • 683
sandy
  • 1,153
  • 7
  • 21
  • 39
  • 2
    You won't be able to construct this regex. Well, In theory you could, but it won't be neither simple nor readable and maintainable. Why won't you just examine the password string char by char and see if it meets the requirements? – J0HN Mar 13 '13 at 13:33
  • Basically *a* regular expression is not the right tool for the job. – kjetilh Mar 13 '13 at 13:45
  • 3
    @J0HN: I beg to differ. Those things are quite easy to express in a regular expression. And it's not really harder to read or maintain than one or several loops that check each character. Except probably for regex-illiterate people. But you can always add comments to explain intent. – Joey Mar 13 '13 at 14:42
  • possible duplicate of [javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase](http://stackoverflow.com/questions/14850553/javascript-regex-for-password-containing-at-least-8-characters-1-number-1-uppe) – Bergi Mar 13 '13 at 14:56
  • @Joey, Ok, you've just converted me to your religion :) I haven't thought of lookaheads :) Actually I love regexes, when they used in a proper way. Hoverwer [there are some reason](http://stackoverflow.com/questions/7844359/password-regex-with-min-6-chars-at-least-one-letter-and-one-number-and-may-cont) behind using string loop in such a case. – J0HN Mar 13 '13 at 14:58

1 Answers1

2

You can solve these with a combination of lookaheads:

  1. (?=.*[a-zA-Z])
  2. (?=.*\d)
  3. .{8}
  4. (?=.*[^\da-zA-Z])

The last one just requires a non-letter and non-digit which is probably by far the easiest way of specifying that you want a somewhat “special” character.

So in the end you have

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8}$
Joey
  • 344,408
  • 85
  • 689
  • 683