Search code examples
regexpasswordspolicy

Regex issue with setting up a password policy


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


Solution

  • 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