-1

I would like to set up a password policy using Regex. Please help me, if you can. Basically, I would like to be able to have the following password rules being checked against:

  • Password should have at least 12 characters
  • It should have at least 3 lowercase characters
  • It should have at least 3 uppercase characters
  • a number
  • a special character

Thank you so much!

Best wishes,

Marcin

keybald
  • 17
  • 4
  • Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – revo Mar 12 '18 at 12:21
  • You may benefit from [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/) – ctwheels Mar 12 '18 at 13:44
  • Thank you ctwheels for your very valuable input. Have a good day. – keybald Mar 12 '18 at 14:32

1 Answers1

0

Although question must be reviewed, positive lookahead are zero width assertion and so can be useful to combine AND conditions. x flag used to increase readability.

^
(?=.{12,})                  # at least 12 characters
(?=(?:[^a-z]*[a-z]){3,})    # at least 3 lowercase characters
(?=(?:[^A-Z]*[A-Z]){3,})    # at least 3 uppercase characters
(?=(?:[^0-9]*[0-9]){1,})    # a number
(?=(?:[^ -\/:-@[-`{-~]*[ -\/:-@[-`{-~]){1,}) # a special character
.*$                         # to get the match

check on regex101

Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
  • Thank you so much. This is exactly what I was looking for. Have a good day. – keybald Mar 12 '18 at 13:01
  • No need to use `{3,}` since you're checking only that it satisfies `{3}`. It's just extra processing for no reason. Same goes for `{12,}` and `{1,}` (which is actually the same as `+`, but you don't need a quantifier here. Also, just remove the first lookahead and make it part of the pattern instead `.{12,}$`. – ctwheels Mar 12 '18 at 13:42
  • Also, you shouldn't limit special characters to a specific subset of them. This decreases password strength and effectively allows attackers to exploit character limitations in passwords. – ctwheels Mar 12 '18 at 13:51