Blog / Tutorial
Email Regex Java: Validate Email Addresses with Regex
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:
- Valid:
[email protected],[email protected],[email protected] - Invalid:
invalid-email@,invalid-email.com,@example.com
Beyond Regex: Verify the Address
A regex only checks format. It can’t tell you whether the mailbox actually exists, whether the domain accepts every address you throw at it, or whether the address is a disposable throwaway. Fuego’s email verification API answers those questions with a real SMTP check, and includes domain intelligence about the company behind the address at no extra cost:
- Verify: a
resultofdeliverable,undeliverable,riskyorunknown, plus areasonlikeaccepted_emailorinvalid_domain - Flag risky signups:
disposable,role,freeandaccept_allflags - Fix typos: a
did_you_meansuggestion for mistakes likegmial.com - Know the company: a free
domain_insightobject with the organization’s name, industry, employee count and country
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/verify?email=" + email + "&token=" + token);
HttpResponse<String> response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(uri).GET().build(),
HttpResponse.BodyHandlers.ofString());
// JSON with result, reason, disposable, domain_insight and more
System.out.println(response.body());
}
}
For a full walkthrough, including error handling and caching, see our guide to integrating the Fuego API with Java.
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 know an address is real before you rely on it, add an email verification API. Start a free trial to try it out.
Happy coding!