Reputation: 121
I need a regular expression to check that if a password contains:
I tried multiple approach, but without success. I don't know if I can do this verify with regex. The most accurate pattern is : ^(?=(.*[a-zA-Z]){1,6})(?=(.*[0-9]){1,10})(?=(.*[!@#$%^&*()\-__+.]){0,1})
But it don't work good when I have more than 6 char, 10 digits or 1 special character.
Could anyone help me?
Upvotes: 1
Views: 870
Reputation: 521259
I might not use a single regex pattern, but would instead use multiple checks. For example:
String password = "ABC123@";
int numChars = password.replaceAll("(?i)[^A-Z]+", "").length();
int numDigits = password.replaceAll("\\D+", "").length();
int numSpecial = password.replaceAll("[^!@#$%^&*()_+.-]", "").length();
if (numChars >=1 && numChars <= 6 && numDigits >= 1 && numDigits <= 10 &&
numSpecial <= 1) {
System.out.println("password is valid");
}
else {
System.out.println("password is invalid");
}
Upvotes: 3