password policy with regular expression

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: