Thursday, April 22, 2010

Pattern Matching for Password

Java introduced Pattern matching API from JDK 1.4 onwards. Its definitely a wonderful API for validating passwords, userId, etc in an application. There are some predefined regular expressions available. Here, Iam going to explain a regular expression for password validation.

You would have encountered password rules in several websites. Lets see how the regular expression is going to be for the following password rule:
It should contain at least one digit from 0-9
It should contain at least one letter from A-Z
It should not contain any lower case letter
The minimum length of the username must be 6 characters and the maximum may be 20.
It should contain at least one character from amongst @#*=
It should not contain any spaces

Regular Expression for the above conditions :

  • (?=.*[@#*=]) # must contains one special character "@#$%"
  • (?=.*[A-Z]) # must contains one UPPER Case Character
  • (?!.*[a-z]) # must not contain lower case Character (See ! instead of =)
  • (?=.*[0-9]) # must contains one number 0-9
  • (?!.*\\s) # must not contain any spaces
  • . # match anything with previous condition checking
  • {6,20} # length at least 6 characters and maximum of 20

Java Pattern Matching Code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class UserName
public static void main(String[] args)
String password="ABC3a#@@";
Pattern pattern = Pattern.compile("(?=.*[@#*=])(?=.*[A-Z])(?!.*[a-z])(?=.*[0-9])(?!.*\\s).{6,20}$");
Matcher m = pattern.matcher(userName);
boolean b = m.matches();
if (b==false)
else if(b==true)

No comments: