不,它不是很漂亮,但是您可以像这样使用蛮力使用单个正则表达式有效地做到这一点(假设 C#):
正则表达式匹配 4 个密码条件中的 2 个:
Regex re = new Regex(@"
# Match 2 of 4 passwords criteria and length from 8 to 24.
^ # Anchor to start of string.
(?: # Group acceptable pair alternatives.
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=[^a-z]*[a-z]) # At least one Lower Case.
| # or...
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=[^0-9]*[0-9]) # At least one Numeric.
| # or...
(?=[^A-Z]*[A-Z]) # At least one Upper Case.
(?=\w*\W) # At least one Non-AlphaNumeric.
| # or...
(?=[^a-z]*[a-z]) # At least one Lower Case.
(?=[^0-9]*[0-9]) # At least one Numeric.
| # or...
(?=[^a-z]*[a-z]) # At least one Lower Case.
(?=\w*\W) # At least one Non-AlphaNumeric.
| # or...
(?=[^0-9]*[0-9]) # At least one Numeric.
(?=\w*\W) # At least one Non-AlphaNumeric.
) # Brute force!
.{8,24} # Match from 8 to 24 chars.
\z # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace);
if (re.IsMatch(text)) {
// Password is valid.
} else {
// Password is NOT valid.
}
4 个要求中的 2 个有六种可能的组合。最后的.{8,24}
长度检查假定除换行符以外的任何字符都可以(您可能/应该想要修改它)。
编辑:我现在看到 dbaupp 的答案工作得很好(我给了它我的赞成票)。尽管我查找大写字母的表达式:(?=[^A-Z]*[A-Z])
比: 更有效(?=.*[A-Z])
(其他前瞻也是如此)。另一方面,dbaupp 的答案在分组方面更有效。