Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - regular expression for strong password

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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-Zdp{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-Zdp{P}]*$) # or the inverse of the above
.{6,}       # Match at least six characters
$           # End of string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...