Regex for Passwords

Regex for Passwords

Useful but awful

Regex patterns, whether you love them or hate them, they are helpful. They enable the developer to define patterns for data validation, ease the extraction of sections from strings and documents, and much more.

Password validation pattern

Note: The following expression checks “2 each” of (uppercase, lowercase, 0-9)

^(?=.{8,50}$)(?=(.*[A-Z]){2})(?=(.*[a-z]){2})(?=(.*[0-9]){2})(?=\\S+$).*$

otherwise,

^(?=(?:\\D*\\d){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2})(?=\\S+$).{8,50}$

And, the following checks “any 2” of (uppercase, lowercase, 0-9, defined set of special symbols)

^(?=.{8,50}$)(?=([A-Z,a-z,0-9,[!,~,*,$]]+){2})(\\S+$)$

What does it all mean?

(?=.{8,50}$) (?= ANDs the condition to rest of conditions that follows), this condition checks for the length of input from 8 to 50.

(?=(.*[A-Z]){2}) (where, .* any character 0 or more times, followed by UPPERCASE letter) and {2}, means by condition should apply twice; therefore, UPPERCASE letter exists twice.

(?=(.*[a-z]){2}) (where, .* means any character 0 or more times, followed by LOWERCASE letter) and {2}, means by condition should apply two times, therefore LOWERCASE letter twice.

(?=(.*[0-9]){2}) (where, .* means any character 0 or more times, followed by DIGIT ) and {2}, means by condition should apply two times, therefore DIGIT exists 2 times

(?=\\S+$) (where \S means non-whitespace, + means 0 or more times, so it checks if all characters are non-whitespace characters. So if a space comes, this condition will fail.

NOTE:“\” I used for an escape character .* this is the last condition, which means any other character after my last check (e.g. digit in my case, so it is not just that the last character should be a digit).

NOTE: If there is only 1 or last condition, we don’t use ?= to AND.

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.