A password is validate if:
It contains at least 8 characters and at most 15 characters.
It contains at least one lower case alphabet.
It contains at least one upper case alphabet.
It contains at least one digit.
It contains at least one special character i.e. !@#$%&*()-+=^.
It does not contain space.
Code:
Import library:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Create a Password class
class Password
{
}
Create a regular expression to check a password is valid or not.
public static final Pattern PASSWORD_REGEX = Pattern.compile("^(?=.*[0-9])"
+ "(?=.*[a-z])(?=.*[A-Z])"
+ "(?=.*[@#$%^&+=])"
+ "(?=\\S+$).{8,15}$");
Add a validatePassword method
public static String validatePassword(String str)
{
// System.out.println(str);
Matcher matcher = PASSWORD_REGEX.matcher(str);
return matcher.find()?"":" not";
}
Main method
public static void main(String[] args)
{
String[] str = new String[]{"pollard@123A","Tesl@112","Park","Fest@4","TSHIRT","Ramesh123"};
for(int i=0;i<str.length;i++)
{
System.out.println("The password "+str[i]+" is"+validatePassword(str[i])+" validate");
}
}
Output:
nice explaination.