Validating Email with Regex in Java

  • Last updated Apr 25, 2024

In this tutorial, you will learn how to validate an email using regular expressions (regex) in Java. Email validation is a common requirement in many applications to ensure that user-provided email addresses adhere to a specific format.

Here's an example code snippet that demonstrates how to validate an email using regex in Java:

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

public class Example {

   public static final String REGEX_EMAIL = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

   public static void main(String[] args) {
       String email = "";
       if (validateEmail(email)) {
	   System.out.println("Email is valid.");
       } else {
	   System.out.println("Email is invalid.");

   public static final boolean validateEmail(String email) {
       Pattern p = Pattern.compile(REGEX_EMAIL);
       Matcher m = p.matcher(email);
       return m.matches();

When you run this program, you will see the following output:

Email is invalid.

In this example, we define a class called Example that contains a validateEmail method responsible for validating the email using a regex pattern. The regex pattern ^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$ ensures that the email address starts with one or more alphanumeric characters, followed by @, and then followed by one or more alphanumeric characters, dots, or hyphens. The validateEmail method accepts email as a parameter and returns true if the email is valid and false otherwise.