การ validate สตริงให้มีเฉพาะตัวอักษร a-z, A-Z สามารถทำได้ 2 วิธีหลัก:
วิธีที่ 1: วนลูปตรวจสอบตัวอักษรทีละตัว
import java.util.Scanner;
public class ValidatingString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String str = sc.next();
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z')) {
flag = false;
break; // หยุดทันทีที่พบตัวอักษรไม่ถูกต้อง
}
}
if (flag) {
System.out.println("Given string is a proper name.");
} else {
System.out.println("Given string is not a proper name.");
}
}
}
ผลลัพธ์
Enter your name: krishna45
Given string is not a proper name.
Enter your name: kasyap
Given string is a proper name.
วิธีที่ 2: ใช้ Regular Expression (แนะนำ)
Regex ^[a-zA-Z]*$ หมายถึง: เริ่มต้น (^) จบ ($) มีแต่ตัวอักษร a-z หรือ A-Z เท่านั้น (* = 0 หรือมากกว่า)
import java.util.Scanner;
public class ValidatingString2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String str = sc.next();
if (str != null && str.matches("^[a-zA-Z]*$")) {
System.out.println("Given string is a proper name.");
} else {
System.out.println("Given string is not a proper name.");
}
}
}
ผลลัพธ์
Enter your name: krishna45
Given string is not a proper name.
Enter your name: kasyap
Given string is a proper name.
Regex Pattern ต่างๆ สำหรับการ Validate
| Pattern | ความหมาย |
|---|---|
^[a-zA-Z]+$ | อย่างน้อย 1 ตัวอักษร (ไม่ยอมรับสตริงว่าง) |
^[a-zA-Z\\s]+$ | อนุญาตเว้นวรรค (เหมาะสำหรับชื่อ-นามสกุล) |
^[a-zA-Z0-9]+$ | ตัวอักษร + ตัวเลข (alphanumeric) |
^[\\p{L}]+$ | ตัวอักษรทุกภาษา (Unicode letter) - รองรับไทย, จีน, ฯลฯ |
ข้อแนะนำ
- ใช้
matches()กับ regex สำหรับโค้ดกระชับ อ่านง่าย - ใช้
Pattern.compile()แบบ static final หาก validate บ่อยๆ เพื่อประสิทธิภาพ - สำหรับชื่อคนจริง ควรอนุญาตเว้นวรรค, hyphen, apostrophe ด้วย