Blog / Tutorial

Email Regex Java: Validate Email Addresses with Regex

Fuego Team /

Validating email addresses is a common task for software engineers and marketers. One efficient way to achieve this in Java is by using regular expressions (regex). This tutorial will guide you through setting up a ‘good enough’ regex for email validation in Java, providing code examples and explaining the expected outputs.

Why “Good Enough” Matters

While it is technically possible to create a regex pattern that adheres strictly to the email format defined by RFC 5322, such patterns tend to be overly complex and practically difficult to manage. Instead, a “good enough” regex can be simpler to implement and can handle the majority of real-world email addresses correctly.

Java Regex for Email Validation

Below is a practical regex example that covers common email formats:

^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$

This regex will match most email addresses while maintaining simplicity. Let’s break it down:

  • ^ - start of the string
  • [A-Za-z0-9+_.-]+ - one or more alphanumeric characters, +, ., _, and -
  • @ - an “at” symbol separating the local part and the domain part
  • [A-Za-z0-9.-]+ - one or more alphanumeric characters, . and -
  • $ - end of the string

Java Implementation

Here is a simple Java class that uses our regex to validate email addresses. The pattern is compiled once and reused, which is faster than compiling it on every call:

import java.util.regex.Pattern;

public class EmailValidator {

    private static final Pattern EMAIL_PATTERN =
        Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");

    public static boolean isValidEmail(String email) {
        return EMAIL_PATTERN.matcher(email).matches();
    }

    public static void main(String[] args) {
        String[] testEmails = {"[email protected]", "[email protected]", "[email protected]", "invalid-email@", "invalid-email.com", "@example.com"};

        for (String email : testEmails) {
            System.out.println(email + " : " + isValidEmail(email));
        }
    }
}

Expected Output

Running the above code, you should see:

[email protected] : true
[email protected] : true
[email protected] : true
invalid-email@ : false
invalid-email.com : false
@example.com : false

Explanation of Results

Our regex correctly validates common email formats while rejecting obviously invalid ones:

Beyond Regex: Know Who Just Signed Up

Even though a regex can handle a wide range of format-validation tasks, it has its limitations. It can’t tell you whether an address is a disposable throwaway, whether its domain has DNS MX records, or whether the person signing up works at an enterprise your sales team should hear about. Fuego’s lead enrichment API answers those questions with one call, fast enough to run inside your signup flow:

  • Segment: the organization behind the address and its category (enterprise, smb, education, government, nonprofit or individual), plus its name, industry, employee count and country
  • Block abuse: disposable, role and free flags, a DNS-only has_mx check, and a simple risk level
  • Fix typos: a did_you_mean suggestion for mistakes like gmail.cmo

Here’s a call using the HTTP client built into Java 11 and later:

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class FuegoExample {
    public static void main(String[] args) throws Exception {
        String email = URLEncoder.encode("[email protected]", StandardCharsets.UTF_8);
        String token = URLEncoder.encode(System.getenv("FUEGO_KEY"), StandardCharsets.UTF_8);
        URI uri = URI.create("https://app.gofuego.io/api/v1/enrich?email=" + email + "&token=" + token);

        HttpResponse<String> response = HttpClient.newHttpClient().send(
            HttpRequest.newBuilder(uri).GET().build(),
            HttpResponse.BodyHandlers.ofString());

        // JSON with category, risk, disposable, organization and more
        System.out.println(response.body());
    }
}

Pairing regex with an enrichment API lets you block junk signups and route your best leads the moment they arrive.

Conclusion

Regex is a powerful tool for basic email format validation in Java. The “good enough” approach we demonstrated balances complexity with practical utility, catching most common email formats. To go beyond format and understand who’s actually signing up, add a lead enrichment API. Start a free trial to try it out.

Happy coding!

Segment your next signup in under 200ms

Start a free trial today. No survey, no scraped data, no lost signups.