Interface java.util.regex.MatchResult เมธอด group(int group) คืนค่าสตริงที่จับคู่ได้ในกลุ่ม (group) ที่ระบุ จากการจับคู่ล่าสุด
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
public static void main(String args[]) {
String regex = "(.*)(\\d+)(.*)";
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
String matchedData = res.group(2); // กลุ่มที่ 2
System.out.println(matchedData);
}
}
ผลลัพธ์
Enter input text: This is a sample Text, 123
Match found
3
อธิบาย
- Input: "This is a sample Text, 123"
- Regex:
(.*)(\\d+)(.*)- 3 capturing groups - Group 1:
(.*)= "This is a sample Text, 12" (greedy) - Group 2:
(\\d+)= "3" (ตัวเลขตัวสุดท้าย) - Group 3:
(.*)= "" (ว่าง) res.group(2)คืน "3"
การนับกลุ่ม (Group Numbering)
- Group 0 = ทั้งหมดที่จับคู่ได้ (entire match)
- Group 1, 2, 3... = capturing groups ตามลำดับวงเล็บเปิด
(จากซ้ายไปขวา - Non-capturing groups
(?:...)ไม่นับ
ตัวอย่าง Group Numbering
Regex: ((A)(B))(C)
Index: 1 2 3 4
Group 0: (A)(B)(C) - ทั้งหมด
Group 1: (A)(B) - วงเล็บนอกสุด
Group 2: A - วงเล็บในซ้าย
Group 3: B - วงเล็บในขวา
Group 4: C - วงเล็บสุดท้าย
MatchResult vs Matcher
Matcher.group(int)- ใช้กับ matcher ปัจจุบัน (stateful)MatchResult.group(int)- ใช้กับ snapshot (immutable) จากtoMatchResult()- MatchResult ปลอดภัยกว่าสำหรับ multi-threading หรือเก็บไว้ใช้ภายหลัง