How do I validate email address using regular expression?

In this examples we use the String‘s class matches() methods to match a string to be a valid email address based on the given regex.

This examples also demonstrate the power of regular expression to validate an email address. Using regular expression makes it easier to validate data such as email. After the code you’ll see the meaning of the regular expression used in the code below.

package org.kodejava.example.lang;

public class EmailAddressValidation {
    private static final String EMAIL_REGEX =
        "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    public static void main(String[] args) {
        EmailAddressValidation validator = new EmailAddressValidation();

        System.out.println("isValid = "
            + validator.isValidEmailAddress("user@domain.com"));
        System.out.println("isValid = "
            + validator.isValidEmailAddress("user.name@domain.com"));
        System.out.println("isValid = "
            + validator.isValidEmailAddress("user.name@domain.com.sg"));
        System.out.println("isValid = "
            + validator.isValidEmailAddress("user.domain.com.sg"));
    }

    /**
     * Validates email address against email regular expression.
     *
     * @param email an email address to check
     * @return true if email address is valid otherwise return false.
     */
    private boolean isValidEmailAddress(String email) {
        return email.matches(EMAIL_REGEX);
    }
}

The first ^[\w-_\.+]. The ^ symbols means check the first character. This the regex processor that the email address should start with a word character formed of alphanumeric value (a-z 0-9) or it can also be an hyphen, underscore, dot or a plus symbol.

The second part, *[\w-_\.]. The * symbol means match the preceding zero or more times. As the first part, this tell the regex processor to check for another zero or more characters, and it can also contains hyphen, underscore and a dot.

The third part, \@([\w]+\.)+. This check that email address should contains the @ symbol followed by one or more word separated by the dot symbol.

The last part is, [\w]+[\w]$, this check that after the last period there should be another word for the domain suffix such as the co.uk or co.id. And the $ ask that the email address should ends by a word character.

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply