Java Regex Email Example

This Java regex example demonstrates how to use Java regular expressions to validate email addresses with an example.

Java Regex email example

In the following example, we create a regex pattern for checking email addresses. This example provides only one possible solution.
package net.javaguides.corejava.regex;

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

public class JavaRegexEmail {

    public static void main(String[] args) {

        List < String > emails = Arrays.asList("",
            "tom@yahoocom", "34234sdfa#2345", "");

        String regex = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,18}$";

        Pattern p = Pattern.compile(regex);

        for (String email: emails) {

            Matcher m = p.matcher(email);

            if (m.matches()) {
                System.out.printf("%s matches%n", email);
            } else {
                System.out.printf("%s does not match%n", email);
Output: matches
tom@yahoocom does not match
34234sdfa#2345 does not match matches


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course