password policy with regular expression
November 30, 2012 Leave a comment
Password policy to match minimum 8 characters password with alphabets in combination with numbers or special characters
package regexp; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Helper for password policy * * @author ntallapa */ public class PwdPolicyVerifier { private Pattern pattern; private Matcher matcher; /** * password policy to match 8 characters with alphabets in combination with numbers or special characters * * (?=.*[a-zA-Z]) means one or more alphabets, it can be small or CAPS * (?=.*[0-9@#$%]) means one or more numerals or special characters * {8,} means password length should be minimum 8 */ private String pwd_policy = "((?=.*[a-zA-Z])(?=.*[0-9@#$%]).{8,})"; public PwdPolicyVerifier() { pattern = Pattern.compile(pwd_policy); } /** * Verify the validity of the given client password * @param password * @return boolean if test string passed the password policy or not */ public boolean verify(String password) { matcher = pattern.matcher(password); if (matcher.matches()) { System.out.println(password + " matched the regexp"); } else { System.out.println(password + " didnt match the regexp"); } return matcher.matches(); } // some test cases public static void main(String[] args) { PwdPolicyVerifier pv = new PwdPolicyVerifier(); pv.verify("welcome1"); pv.verify("welcomeA"); pv.verify("Welcome@"); pv.verify("12341234"); pv.verify("####$$$$"); pv.verify("Welcome@12"); pv.verify("WELCOME12"); } }
Output:
welcome1 matched the regexp
welcomeA didnt match the regexp
Welcome@ matched the regexp
12341234 didnt match the regexp
####$$$$ didnt match the regexp
Welcome@12 matched the regexp
WELCOME12 matched the regexp
Recent Comments