Regular Expression สำหรับ validate email address:
"^[\\w!#$%&'*/+=?`{|}~^-]+(?:\\.[\\w!#$%&'*/+=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String input = sc.nextLine();
String regex = "^[\\w!#$%&'*/+=?`{|}~^-]+(?:\\.[\\w!#$%&'*/+=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
ผลลัพธ์
Enter a String: sample.123@gmail.com
Match occurred
อธิบาย Regex แบบละเอียด
| ส่วน | Regex | ความหมาย |
|---|---|---|
| Local part เริ่มต้น | ^[\\w!#$%&'*/+=?`{|}~^-]+ | ตัวอักษร/ตัวเลข/underscore และสัญลักษณ์พิเศษ 1+ ตัว |
| Dot segments | (?:\\.[\\w!#$%&'*/+=?`{|}~^-]+)* | จุดตามด้วยตัวอักษรที่อนุญาต 0+ กลุ่ม (non-capturing) |
| @ symbol | @ | ตัว @ ตรงตัว |
| Domain labels | (?:[a-zA-Z0-9-]+\\.)+ | โดเมนย่อย 1+ ตัว ต่อด้วยจุด (non-capturing) |
| TLD | [a-zA-Z]{2,6}$ | Top-level domain 2-6 ตัวอักษร พิมพ์ใหญ่/เล็ก |
ข้อจำกัด
- Regex นี้เป็นรูปแบบง่าย ไม่ครอบคลุม RFC 5322 ทั้งหมด
- ไม่รองรับ: quoted local part ("user@domain"@example.com), IP domain ([192.168.1.1]), comments, Unicode ใน local part
- TLD จำกัด 2-6 ตัวอักษร (ปัจจุบันมี TLD ยาวกว่า เช่น .museum, .international)
แนวทางที่ดีกว่า (Production)
// ใช้ Apache Commons Validator
EmailValidator validator = EmailValidator.getInstance();
boolean valid = validator.isValid(email);
// หรือ Java 8+ ใช้ pattern 簡易版
String simpleRegex = "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$";
หมายเหตุ
สำหรับ production จริง ควรใช้ library ที่ทดสอบแล้ว (Apache Commons Validator, Hibernate Validator) หรือส่ง verification email ยืนยันความเป็นเจ้าของ