📧 Email Validation Using Java Regular Expressions (Regex)
Topic: Java Regex Pattern for Email Validation
🧩 Overview
In this post, we’ll explore how to validate email addresses in Java using Regular Expressions (Regex).
The regex pattern enforces strict rules for valid email structures — ensuring only properly formatted email IDs are accepted.
🧠 Regex Pattern
🔍 Pattern Breakdown
| Symbol | Meaning | Description |
|---|---|---|
^ | Start of the pattern | Ensures the match begins from the start of the string |
[A-Z0-9._]+ | First part | The local part (before @) must contain uppercase letters (A-Z), digits (0-9), and . or _ |
@ | Separator | Separates the username and domain parts |
[A-Z0-9-]+ | Second part | The domain name (after @) must contain letters, digits, or hyphens (-) |
\.[A-Z]{2,6} | Third part | The domain extension must begin with a . followed by 2 to 6 letters (A-Z) |
$ | End of the pattern | Ensures the match ends at the end of the string |
🧩 In simple terms:
The email must look like
USERNAME@DOMAIN.TLD,
where:
Username = letters, numbers, dots, or underscores
Domain = letters or numbers
TLD (Top-Level Domain) = 2–6 letters only (e.g.,
.com,.org,.co.in)
🧰 Java Implementation
Here’s the complete Java example to validate emails using this regex pattern.
🧪 Sample Output
✅ Explanation of Results
| Expected Result | Reason | ||
|---|---|---|---|
kkvinod@pretechsol.com | ✅ true | Valid format | |
kkvin%od@pretechsol.com | ❌ false | % not allowed before @ | |
kkvinod@prete_chsol.com | ❌ false | _ not allowed in domain name | |
kkvinod@pretechsol.comcomcom | ❌ false | TLD (extension) exceeds 6 letters |
No comments:
Post a Comment