Requires a Reg expression for a strong password

Can someone help me with a regex for password with the following please.

include at least two of the following values:

lowercase letter
uppercase letter
number
"special character" (e.g. £, $, &, #)

+6
source share
3 answers

As Kate Thompson said in a comment, I don’t think there is one regex here.

The following code will do what you want, and I think it is more readable, easy to maintain, and easier to prove correct than a single regular expression:

string password = "123abc"; string[] regexes = new[] { "[az]", //any lowercase word "[AZ]", //any uppercase word @"\d", //any digit @"\W" //special characters (or just [£$&#], adding the characters you want) }; bool isValid = regexes.Count(regex => Regex.IsMatch(password, regex)) >= 2; 
+1
source

The following should work:

 ^(?![az]*$|[AZ]*$|\d*$|[\W_]*$).*$ 

Example: http://www.rubular.com/r/effCmvehdx

A negative lookahead at the beginning will crash if the entire line consists of just one group.

Please note that even if it meets your requirements, it is not a good regular expression for a strong password. You probably also need a length check, and you can require at least three such groups instead of two.

+4
source

As I said in a comment, regex is almost certainly not suitable for this job. It will be much easier to write code that iterates over password characters by counting the number of characters in each class.

You have not defined what a "special character" is. I guess this means any character other than a letter or number (including spaces and control characters). I also suggest that the “letters” refer to only 26 letters of the English alphabet, which means that a non-English letter like ñ is a special character.

To take a simpler example, regular expressions don't really express things like "foo and bar in any order"; you must explicitly specify both orders:

  foo.*bar|bar.*foo 

In this case, you need 12 different options. I think this is correct, but I have not tested it.

 [az].*[AZ}|[AZ].*[az}|[az].*[0-9]|[0-9].*[az]|[az].*[^a-zA-Z0-9]|[^a-zA-Z0-9].*[az]|[AZ].*[0-9]|[0-9].*[AZ]|[AZ].*[^a-zA-Z0-9]|[^a-zA-Z0-9].*[AZ]|[0-9].*[^a-zA-Z0-9]|[^a-zA-Z0-9].*[0-9] 

This is a regular expression such as egrep or Perl. grep does not recognize | default; if you need a grep line regular expression, replace each | on \| .

And if changing requirements, say, require at least 3 out of 5 character classes, you need to completely rewrite the regular expression; you cannot just configure it.

Please note that your requirements still allow Aa .

+1
source

All Articles