问题
I need to do this following password validation in Java
- Must be at least 8 characters in length
- Must contain at least 1 number
- Must contain at least 1 upper case letter
- Must contain at least 1 lower case letter
- Cannot contain 3 or more consecutive characters from your full name or your username (e.g. If your name is
Will
you couldn't have the passwordStiller458
)
I have the first 4 points, how do I do the last one?
Currently I have:
String pattern = "^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])\\S{8,}$";
boolean passwordValidation = originalPassword.matches(pattern);
回答1:
For your 1,2,3,4 case
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}$
For your 5th case
public boolean isValid(final String userName,final String password)
{
for(int i=0;(i+2)<userName.length();i++)
if(password.indexof(userName.substring(i,i+2))!=-1)
return false;
return true;
}
回答2:
The last point is not something you do with regex. Loop through the name and check against the password instead.
Regex is good at patterns, not parsing. One way or another you have to use a loop to go through the name.
来源:https://stackoverflow.com/questions/16797636/validate-that-password-doesnt-contain-3-consecutive-characters-from-name