Regular Expression (Regex) คือลำดับตัวอักษรพิเศษที่ช่วยให้คุณจับคู่หรือค้นหาสตริงหรือชุดของสตริงได้ โดยใช้ไวยากรณ์เฉพาะที่ถูกเก็บไว้ในรูปแบบ (pattern)
กลุ่มการจับคู่ (Capturing Groups) คืออะไร
กลุ่มการจับคู่ใน Regular Expression ใช้เพื่อจัดกลุ่มตัวอักษรหลายตัวให้เป็นหน่วยเดียว โดยแสดงด้วยวงเล็บ () กล่าวคือ หากคุณวางหลาย sub-patterns ไว้ภายในวงเล็บ พวกมันจะถูกจัดการเป็นกลุ่มเดียว
ตัวอย่างเช่น รูปแบบ [0-9] จับคู่กับตัวเลข 0 ถึง 9 และรูปแบบ {5} จับคู่กับตัวอักษร 5 ตัว หากจัดกลุ่มทั้งสองเป็น ([0-9]{5}) จะจับคู่กับหมายเลข 5 หลักได้
ตัวอย่างที่ 1: ตรวจสอบรูปแบบวันที่
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroupExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your Date of birth: ");
String dob = sc.nextLine();
// Regular expression สำหรับรับวันที่ในรูปแบบ MM/DD/YYYY
String regex = "^(1[0-2]|0[1-9])/" // สำหรับเดือน
+ "(3[01]|[12][0-9]|0[1-9])/" // สำหรับวัน
+ "[0-9]{4}$"; // สำหรับปี
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if (result) {
System.out.println("Given date of birth is valid");
} else {
System.out.println("Given date of birth is not valid");
}
}
}
ผลลัพธ์
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid
ตัวอย่างที่ 2: การใช้กลุ่มการจับคู่เพื่อแยกส่วนของข้อความ
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
public static void main(String[] args) {
String regex = "(.*)(\\d+)(.*)";
String input = "This is a sample Text, 1234, with numbers in between.";
// สร้าง pattern object
Pattern pattern = Pattern.compile(regex);
// จับคู่ pattern ที่คอมไพล์แล้วในสตริง
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("match: " + matcher.group(0));
System.out.println("First group match: " + matcher.group(1));
System.out.println("Second group match: " + matcher.group(2));
System.out.println("Third group match: " + matcher.group(3));
}
}
}
ผลลัพธ์
match: This is a sample Text, 1234, with numbers in between. First group match: This is a sample Text, 123 Second group match: 4 Third group match: , with numbers in between.
สรุป
- กลุ่มการจับคู่ช่วยให้จัดกลุ่มส่วนของ regex ให้เป็นหน่วยเดียว
- สามารถอ้างอิงกลุ่มที่จับคู่ได้ผ่าน
matcher.group(n)โดย n = 0 คือทั้งหมด, 1, 2, 3... คือกลุ่มที่ 1, 2, 3... - มีประโยชน์มากสำหรับการแยกข้อมูล เช่น วันที่ หมายเลขโทรศัพท์ อีเมล ฯลฯ