Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมธอด MatchResult group (int group) ใน Java พร้อมตัวอย่าง


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 GroupExample {
   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();
      String matchedData = res.group(2);
      System.out.println(matchedData);
   }
}

ผลลัพธ์

Enter input text:
This is a sample Text, 123
Match found
3