Matching Email Addresses with Regex
What you'll learn: You'll build a practical regular expression pattern to validate email addresses, applying character classes and quantifiers to handle real-world input.
The Challenge of Email Validation
Email addresses follow a specific structure: something before the @ symbol (the local part), followed by a domain name with at least one dot. While fully RFC-compliant email validation is extremely complex, a practical regex pattern can catch most common cases and user errors.
Building the Pattern Step by Step
A reasonable email pattern looks like this:
String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
Pattern pattern = Pattern.compile(emailPattern);
Breaking it down:
^and$– Anchors ensuring the entire string matches (crucial for validation)[A-Za-z0-9+_.-]+– Character class matching one or more valid local-part characters@– The literal @ symbol (required separator)[A-Za-z0-9.-]+– One or more valid domain characters before the dot\\.– Escaped literal dot (since.normally matches any character)[A-Za-z]{2,}– Quantifier requiring at least 2 letters for the top-level domain
Using It for Validation
Matcher matcher = pattern.matcher("user@example.com");
if (matcher.matches()) {
System.out.println("Valid email");
}
matcher.reset("invalid@domain"); // Missing TLD
if (!matcher.matches()) {
System.out.println("Invalid: no top-level domain");
}
Notice we use matches() not find() — we're validating the entire input string against the format, not searching within text.
Key Takeaway: Email validation regex combines character classes ([A-Za-z0-9...]) to define allowed characters with quantifiers (+, {2,}) to specify how many, anchored with ^ and $ to ensure complete string validation using matches().