How do I validate email address using regular expression?

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

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

package org.kodejava.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("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("user.domain.co.id"));
    }

    /**
     * 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 a 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 contain hyphen, underscore and a dot.

The third part, \\@([\\w]+\\.)+. This check that email address should contain 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 end by a word character.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.