How to Validate Password with Regular Expression in Java


In this example, let’s us see how to validate password with regular expression in Java.

Source Code

package com.beginner.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePassword {
	
	private static final String PASSWORD_PATTERN = 
            "((?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

	public static void main(String[] args) {
		
		String testPassWord1 = "hujashdfu@H156";
		String testPassWord2 = "jisdjf";
		String testPassWord3 = "hujashdfuH156";
		
		System.out.println(validate(testPassWord1));
		System.out.println(validate(testPassWord2));
		System.out.println(validate(testPassWord3));
	}
	
	public static boolean validate(final String password){
		Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
		Matcher  matcher = pattern.matcher(password);
		return matcher.matches();
	  }

}

Output:

true
false
false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Validate Password with Regular Expression in Java


Here this example will show how to validate password with regular expression.

Source Code

package com.beginner.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePassword {
	
	private static final String PASSWORD_PATTERN = 
            "((?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

	public static void main(String[] args) {
		
		String testPassWord1 = "hujashdfu@H156";
		String testPassWord2 = "jisdjf";
		String testPassWord3 = "hujashdfuH156";
		
		System.out.println(validate(testPassWord1));
		System.out.println(validate(testPassWord2));
		System.out.println(validate(testPassWord3));
	}
	
	public static boolean validate(final String password){
		Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
		Matcher  matcher = pattern.matcher(password);
		return matcher.matches();
	  }

}

Output:

true
false
false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments