Archives: Regex

Java – Date Validation with Regular Expression

Date Format (dd/mm/yyyy) Regular Expression Pattern


The above regular expression is used to validate the date format in “dd/mm/yyyy”, you can easy customize to suit your need. However, it’s a bit hard to validate the leap year, 30 or 31 days of a month, we may need basic logic as below.

Java – Password Validation with Regular Expression

Password Regular Expression Pattern:



( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[A-Z]) # must contains one uppercase characters
(?=.*[@#$%]) # must contains one special symbols in the list “@#$%”
. # match anything with previous condition checking
{6,20} # length at least 6 characters and maximum of 20
) # End of group

?= – means apply the assertion condition, meaningless by itself, always work with other combination

Whole combination is means, 6 to 20 characters string with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”). This regular expression pattern is very useful to implement a strong and complex password.

[code lang=”java”]import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PasswordValidator {

private Pattern pattern;
private Matcher matcher;

private static final String PASSWORD_PATTERN =

public PasswordValidator() {
pattern = Pattern.compile(PASSWORD_PATTERN);

* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
public boolean validate(final String password) {

matcher = pattern.matcher(password);
return matcher.matches();



Java – Username Validation with Regular Expression

Username Regular Expression Pattern:   ^[a-z0-9_-]{3,15}$

^     # Start of the line
[a-z0-9_-]  # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
{3,15}      # Length at least 3 characters and maximum length of 15
$       # End of the line