ที่ java.util.regex.MatcheResult อินเทอร์เฟซมีวิธีการดึงผลลัพธ์ของการแข่งขัน
คุณสามารถรับออบเจ็กต์ของอินเทอร์เฟซนี้โดยใช้ toMatchResult() วิธีการของ ตัวจับคู่ ระดับ. เมธอดนี้ส่งคืนออบเจ็กต์ MatchResult ซึ่งแสดงถึงสถานะการจับคู่ของตัวจับคู่ปัจจุบัน
จบ(กลุ่ม int) เมธอดของอินเทอร์เฟซนี้ยอมรับจำนวนเต็มที่แสดงถึงกลุ่มใดกลุ่มหนึ่งและคืนค่าออฟเซ็ตก่อนการจับคู่ครั้งแรกจะเกิดขึ้นในกลุ่มที่ระบุ
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
String regex = "(.*)(\\d+)(.*)";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
int start = res.start(2);
System.out.println(start);
}
} ผลลัพธ์
Enter input text: This is a sample Text, 123 Match found 25