密码的正则表达式

0 regex asp.net

有些人可以通过以下规则给我正确的密码表达.

密码长度至少应为7个字符.它应包含最少3位数字和一个字母字符.密码可以接受任意次数的数字,字母,特殊字符,但数字应至少为3.

LBu*_*kin 8

正则表达式不是特别擅长确保特定字符组出现一定次数.虽然它可能是可能的 - 但毫无疑问它会令人费解并且不明显.

如果您使用.NET(C#或VB)进行编程,则可以使用简单的验证函数,例如:

bool ValidatePasswordCompliance( string password )
{
    int countDigits = 0;
    int countAlpha  = 0;
    int countOthers = 0;
    foreach( char c in password )
    {
         countDigit += c.IsDigit ? 1 : 0;
         countAlpha += c.IsAlpha ? 1 : 0;
         countOther += !(c.IsAlpha || c.IsDigit) ? 1 : 0;
    }
    return countDigits >= 3 && (countDigits + countAlpha + countOthers) >= 7;
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是.NET 3.5或更高版本,则可以使用LINQ来简化此操作:

bool ValidatePasswordCompliance( string password )
{
    return password.Count() >= 7 &&
           password.Count( x => x.IsDigit ) >= 3;
}
Run Code Online (Sandbox Code Playgroud)