java.util.regex.MatcheResult อินเทอร์เฟซมีวิธีการดึงผลลัพธ์ของการแข่งขัน
คุณสามารถรับออบเจ็กต์ของอินเทอร์เฟซนี้โดยใช้ toMatchResult() วิธีการของ ตัวจับคู่ ระดับ. เมธอดนี้ส่งคืนออบเจ็กต์ MatchResult ซึ่งแสดงถึงสถานะการจับคู่ของตัวจับคู่ปัจจุบัน
สิ้นสุด() เมธอดของอินเทอร์เฟซนี้จะคืนค่าออฟเซ็ตหลังจากการจับคู่ครั้งล่าสุดเกิดขึ้น
ตัวอย่าง
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 = "you$";
//Reading input from user
Scanner sc = new Scanner(System.in);
String input = "Hello how are you";
//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 end = res.end();
System.out.println(end);
}
} ผลลัพธ์
Enter input text: hello how are you Match found 17