我建议你的最佳方法是捕获捕获组中的每种类型的字符,并确保至少有3/4个捕获组具有一个值(如果该组不匹配任何内容,它应该是空字符串)。
^(?:([a-z])|([A-Z])|(\d)|(_|[^\w]))+$
您还可以添加一个积极的lookahead,以确保密码具有所需的长度(例如8到32个字符)。
^(?=.{8,32}$)(?:([a-z])|([A-Z])|(\d)|(_|[^\w]))+$
编辑:([\W_])
是(_|[^\w])
等效。将大写字母“W”换成大写字母(匹配所有非单词字符)。此外,使用单个字符类比交替(more details here)
更快,如果你愿意使用JavaScript,我适应在“Regular Expression cookbook second edition”提出了我的网站的需求函数:
var PASSWORD_RANKING = {
TOO_SHORT: 0,
WEAK: 1,
MEDIUM: 2,
STRONG: 3,
VERY_STRONG: 4
};
/**
* Take a password and returns it's ranking
* based of the strength of the password (length, numeric character, alphabetic character, special character, etc.)
*
* @param password String
* @param minLength Int
*
* @return Int
*/
function rankPassword(password, minLength){
var rank = PASSWORD_RANKING.TOO_SHORT;
var score = 0;
if (typeof minLength !== 'number' || minLength < 6){
minLength = 8;
}
if (typeof password === 'string' && password.length >= minLength){
if (/[A-Z]/.test(password)){ score++;}
if (/[a-z]/.test(password)){ score++;}
if (/[0-9]/.test(password)){ score++;}
if (/[[email protected]#$%^&]/.test(password)){ score++;}
score += Math.floor((password.length - minLength)/2);
if (score < 3){
rank = PASSWORD_RANKING.WEAK;
}
else if (score < 4){
rank = PASSWORD_RANKING.MEDIUM;
}
else if (score < 6){
rank = PASSWORD_RANKING.STRONG;
}
else {
rank = PASSWORD_RANKING.VERY_STRONG;
}
}
return rank;
}
4.19节提供了许多强制执行密码强度的正则表达式。您可以在线查看所有代码示例: http://examples.oreilly.com/0636920023630/Regex_Cookbook_2_Code_Samples.html
什么是您的编程语言? –
也是字母和数字只有英文字母和数字,或者你必须支持所有语言? –
我想在Asp.Net中使用RegularExpression属性。是的,只有英文字母。谢谢 – James