negative regex for password review

Viewed 47

I have already tried several options on this topic here on Stackoverflow, but none of them worked.

I have a database of passwords that I need to review for compliance.

I figured how to build an expression to match the passwords that are compliant with the required complexity:

8-32 characters letters numbers special characters

^(?=.*[a-z])(?=.*[A-Z])(?=.*[[:digit:]])(?=.*[[:punct:]]).{8,32}

Now, all I need to do is to get the negative of the above expression to find the password that do not match the required complexity.

I tried to change the expression to this:

(?!^(?=.{8,32}$)(?=.*[[:alpha:]])(?=.*[[:digit:]])(?=.*[[:punct:]])).*

but that does not work.

Thanks for your help

2 Answers

You can reverse your assertion using negative lookahead with alternations like this:

^(?:(?!.*[a-z])|(?!.*[A-Z])|(?!.*[[:digit:]])|(?!.*[[:punct:]])|(?!.{8,32}$)).*

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start non-capture group
    • (?!.*[a-z]): we don't have a lowercase letter ahead
    • |: OR
    • (?!.*[A-Z]): we don't have a uppercase letter ahead
    • |: OR
    • (?!.*[[:digit:]]): we don't have a digit ahead
    • |: OR
    • (?!.*[[:punct:]]): we don't have a punctuation character ahead
    • |: OR
    • (?!.{8,32}$): we don't have 8 to 32 characters ahead
  • ):
  • .*

This regex will highlight bad passwords that are shorter than 8 characters, don't have special characters, upper/lower case letters and numbers:

/^(?:(?!.*[a-z])|(?!.*[A-Z])|(?!.*[[:digit:]])|(?!.*[[:punct:]])|(?!.{8,32}$)|(?!.*[\`\-\=\[\]\;\'\#\,\.\/\\\¬\!\"\£\$\%\^\&\*\(\)\_\+\{\}\:\@\~\<\>\?\|])).*
Related