Regular Expression ที่จับคู่ email รวมถึง input ว่าง (blank):
^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6})?$
อธิบาย Regex
| ส่วน | Regex | ความหมาย |
|---|---|---|
| Start | ^ | เริ่มต้นสตริง |
| Optional group | (... )? | ทั้งกลุ่มเป็น optional (0 หรือ 1 ครั้ง) → รองรับ blank |
| Local part | [a-zA-Z0-9._%+-]+ | อักขระที่อนุญาตก่อน @ (1+ ตัว) |
| @ symbol | @ | ตัว @ ตรงตัว |
| Domain | [a-zA-Z0-9.-]+ | โดเมน: ตัวอักษร ตัวเลข . - (1+ ตัว) |
| Dot + TLD | \\.[a-zA-Z]{2,6} | จุดตามด้วย TLD 2-6 ตัวอักษร |
| End | $ | สิ้นสุดสตริง |
ตัวอย่าง 1: ใช้ Pattern/Matcher
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleTest {
public static void main(String args[]) {
String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6})?$";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your e-mail: ");
String e_mail = sc.nextLine();
System.out.println("Enter your age: ");
int age = sc.nextInt();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(e_mail);
if (matcher.find()) {
System.out.println("e-mail value accepted");
} else {
System.out.println("e-mail not value accepted");
}
}
}
ผลลัพธ์
Enter your name: krishna
Enter your e-mail:
Enter your age: 20
e-mail value accepted
Enter your name: Rajeev
Enter your e-mail: rajeev.123@gmail.com
Enter your age: 25
e-mail value accepted
ตัวอย่าง 2: ใช้ String.matches()
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter email address: ");
String e_mail = sc.nextLine();
String regex = "^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6})?$";
boolean result = e_mail.matches(regex);
if (result) {
System.out.println("Valid match");
} else {
System.out.println("Invalid match");
}
}
}
ผลลัพธ์
Enter email address: rajeev.123@gmail.com
Valid match
Enter email address:
Valid match
ข้อควรระวัง
matcher.find()หา substring ที่จับคู่ → อาจจับคู่บางส่วนของ inputmatcher.matches()หรือString.matches()ต้องจับคู่ ทั้งสตริง- ตัวอย่าง 1 ใช้
find()ซึ่งอาจผ่าน input แปลกๆ เช่น "abc@def.gh extra" (จับคู่แค่ส่วนหน้า) - ควรใช้
matches()สำหรับ validation
ข้อจำกัดของ Regex นี้
- TLD จำกัด 2-6 ตัวอักษร (ไม่รองรับ .museum, .technology, .international)
- ไม่รองรับ internationalized email (Unicode local part, IDN domains)
- ไม่รองรับ quoted strings, comments, IP literals ตาม RFC 5322