Question

I need a regular expression that Contain at least two of the five following character classes:

  • Lower case characters
  • Upper case characters
  • Numbers
  • Punctuation
  • “Special” characters (e.g. @#$%^&*()_+|~-=\{}[]:";'<>/` etc.)

This is I have done so far

int upperCount = 0;
int lowerCount = 0;
int digitCount = 0;
int symbolCount = 0;

for (int i = 0; i < password.Length; i++)
{
    if (Char.IsUpper(password[i]))
        upperCount++;
    else if (Char.IsLetter(password[i]))
        lowerCount++;
    else if (Char.IsDigit(password[i]))
        digitCount++;
    else if (Char.IsSymbol(password[i]))
        symbolCount++;

but Char.IsSymbol is returning false on @ % & $ . ? etc..

and through regex

Regex Expression = new Regex("({(?=.*[a-z])(?=.*[A-Z]).{8,}}|{(?=.*[A-Z])(?!.*\\s).{8,}})");    
bool test= Expression.IsMatch(txtBoxPass.Text);

but I need a single regular expression with "OR" condition.

Was it helpful?

Solution

In other words, you want a password that doesn't just contain one "class" of characters. Then you can use

^(?![a-z]*$)(?![A-Z]*$)(?!\d*$)(?!\p{P}*$)(?![^a-zA-Z\d\p{P}]*$).{6,}$

Explanation:

^           # Start of string
(?![a-z]*$) # Assert that it doesn't just contain lowercase alphas
(?![A-Z]*$) # Assert that it doesn't just contain uppercase alphas
(?!\d*$)    # Assert that it doesn't just contain digits
(?!\p{P}*$) # Assert that it doesn't just contain punctuation
(?![^a-zA-Z\d\p{P}]*$) # or the inverse of the above
.{6,}       # Match at least six characters
$           # End of string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top