This example shows how to validate a Password string in Java using regular expression with Regex Pattern and Matcher validation.
Password Regular Expression Pattern:
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})
Whole combination is means, 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”). This regular expression pattern is very useful to implement a strong and complex password.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator { private Pattern pattern; private Matcher matcher; private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; public PasswordValidator() { pattern = Pattern.compile(PASSWORD_PATTERN); } /** * Validate password with regular expression * @param password password for validation * @return true valid password, false invalid password */ public boolean validate(final String password) { matcher = pattern.matcher(password); return matcher.matches(); } } |