正则表达式用于强密码

6
我需要一个正则表达式,其中至少包含以下五个字符类中的两个:
  • 小写字母
  • 大写字母
  • 数字
  • 标点符号
  • “特殊”字符(例如@#$%^&amp;*()_ + |〜-= \ {} []:“;'<>/`等)
这是我到目前为止所做的。
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++;

但是 Char.IsSymbol 在 @ % & $ . ? 等字符上返回 false。

而通过正则表达式:

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

但我需要一个带有“OR”条件的单一正则表达式。


1
有长度要求吗?目前,1a 是一个有效的密码。 - Tim Pietzcker
另外,您是否认为 éßÄ 是字母? - Tim Pietzcker
1个回答

10
换句话说,您需要一个密码不仅包含一种“类别”的字符。那么您可以使用
^(?![a-z]*$)(?![A-Z]*$)(?!\d*$)(?!\p{P}*$)(?![^a-zA-Z\d\p{P}]*$).{6,}$

解释:

^           # 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

完美地运作了。非常感谢! - Khurram Zulfiqar Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接