Interface java.util.regex.MatchResult มีเมธอดสำหรับดึงผลลัพธ์การจับคู่
ได้ object ของ interface นี้จากเมธอด toMatchResult() ของคลาส Matcher คืนค่า MatchResult ที่แสดงสถานะการจับคู่ปัจจุบัน
เมธอด group() คืนค่าสตริงที่จับคู่ได้ (substring) จาก input sequence ในการจับคู่ล่าสุด
ตัวอย่าง
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();
System.out.println(matchedData);
}
}
ผลลัพธ์
Enter input text: This is a sample Text, 123
Match found
This is a sample Text, 123
อธิบาย
- Regex
(.*)(\\d+)(.*)จับคู่ทั้งสตริง (greedy) matcher.find()หาจับคู่แรกmatcher.toMatchResult()สร้าง MatchResult snapshotres.group()=res.group(0)= ทั้งหมดที่จับคู่ได้
เมธอดหลักของ MatchResult
| Method | คำอธิบาย |
|---|---|
group() | กลุ่มที่ 0 (ทั้งหมด) |
group(int group) | กลุ่มที่ระบุ |
groupCount() | จำนวน capturing groups |
start() | ตำแหน่งเริ่มต้นของกลุ่ม 0 |
start(int group) | ตำแหน่งเริ่มต้นของกลุ่มที่ระบุ |
end() | ตำแหน่งสิ้นสุดของกลุ่ม 0 |
end(int group) | ตำแหน่งสิ้นสุดของกลุ่มที่ระบุ |