我需要验证需要满足以下规则的密码:
我无法弄清楚如何使用正则表达式来验证这一点。有人能帮助我吗?
答案 0 :(得分:5)
^(?=.*[A-Z])(?=.*(?:\d|-))(?!.*(.).*\1)[a-zA-Z]{2}.{4,}[a-zA-Z]{2}$
试试这个。看看演示。
https://regex101.com/r/eZ0yP4/12
正如您所看到的那样,在前瞻的帮助下,所有条件都得到了满足。
(?=.*[A-Z])
===至少有一个资本
(?=.*(?:\d|-))
===至少一位数或-
(?!.*(.).*\1)
===没有重复
[a-zA-Z]{2}.{4,}[a-zA-Z]{2}
===字母字符为前两个和后两个。
答案 1 :(得分:3)
您可以使用vt password library。代码很长,但很容易修改它,并且它非常易于维护。
// password must be between 8 and 16 chars long
LengthRule lengthRule = new LengthRule(8, 16);
// don't allow whitespace
WhitespaceRule whitespaceRule = new WhitespaceRule();
// control allowed characters
CharacterCharacteristicsRule charRule = new CharacterCharacteristicsRule();
// require at least 1 digit in passwords
charRule.getRules().add(new DigitCharacterRule(1));
// require at least 1 non-alphanumeric char
charRule.getRules().add(new NonAlphanumericCharacterRule(1));
// require at least 1 upper case char
charRule.getRules().add(new UppercaseCharacterRule(1));
// require at least 1 lower case char
charRule.getRules().add(new LowercaseCharacterRule(1));
// require at least 3 of the previous rules be met
charRule.setNumberOfCharacteristics(3);
// don't allow alphabetical sequences
AlphabeticalSequenceRule alphaSeqRule = new AlphabeticalSequenceRule();
// don't allow numerical sequences of length 3
NumericalSequenceRule numSeqRule = new NumericalSequenceRule(3);
// don't allow qwerty sequences
QwertySequenceRule qwertySeqRule = new QwertySequenceRule();
// don't allow 4 repeat characters
RepeatCharacterRegexRule repeatRule = new RepeatCharacterRegexRule(4);
// group all rules together in a List
List<Rule> ruleList = new ArrayList<Rule>();
ruleList.add(lengthRule);
ruleList.add(whitespaceRule);
ruleList.add(charRule);
ruleList.add(alphaSeqRule);
ruleList.add(numSeqRule);
ruleList.add(qwertySeqRule);
ruleList.add(repeatRule);
PasswordValidator validator = new PasswordValidator(ruleList);
PasswordData passwordData = new PasswordData(new Password("testpassword"));
RuleResult result = validator.validate(passwordData);
if (result.isValid()) {
System.out.println("Valid password");
} else {
System.out.println("Invalid password:");
for (String msg : validator.getMessages(result)) {
System.out.println(msg);
}
}