java.util.regex.MatcheResult 인터페이스는 일치 결과를 검색하는 메소드를 제공합니다.
toMatchResult()를 사용하여 이 인터페이스의 개체를 가져올 수 있습니다. 매처 메소드 수업. 이 메서드는 현재 matcher의 일치 상태를 나타내는 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