Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

예제가 있는 Java의 MatchResult group() 메서드.

<시간/>

java.util.regex.MatcheResult 인터페이스는 일치 결과를 검색하는 메소드를 제공합니다.

toMatchResult()를 사용하여 이 인터페이스의 개체를 가져올 수 있습니다. 매처 메소드 수업. 이 메서드는 현재 matcher의 일치 상태를 나타내는 MatchResult 개체를 반환합니다.

그룹() 이 인터페이스의 메소드는 마지막 일치에서 주어진 입력 시퀀스에서 일치하는 부분 문자열을 나타내는 문자열 값을 반환합니다.

예시

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();
      System.out.println(matchedData);
   }
}

출력

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