I have the following criteria for creating a regular expression for a password that conforms to the following rules:
- The password must be 8 characters long (this I can do :-)).
The password must then contain characters from at least 3 of the following 4 rules:
- Upper case
- Lower case
- Numbers
- Non-alpha numeric
I can make the expression match ALL of those rules with the following expression:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[\W]).{8,}$/
But I am struggling with how to do this in such a way that it only needs to solve any 3 of the 4 rules.
Can anyone help me out with this?
You could write a really sophisticated regex to do that. Instead, I’d suggest writing four distinct regexes, one for each rule, and testing them one by one, counting how many of them matched. If three out of four did, accept the password.
Don't use one regex to check it then.
If you must use a single regex:
This regex is not optimized for efficiency. It is constructed by
A·B·C + A·B·D + A·C·D + B·C·D
with some factorization. Breakdown:You can use the following Regex:
With a password minimum length of 8 and max length 32 you can use the following Regex:
Id suggest doing the checks seperately, and then just totalling up how many match.
(I'd also not use a regex in any of them, but thats just my personal POV - namely that they hinder readability and are generally write-once code)