Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Phương thức MatchResult group() trong Java


Giới thiệu

java.util.regex.MatchResult interface cung cấp phương thức lấy kết quả match. Lấy object qua matcher.toMatchResult().

Phương thức group()

Trả về substring khớp của toàn bộ match (group 0) trong lần match cuối.

Ví dụ

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+)(.*)";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập văn bản: ");
        String input = sc.nextLine();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            System.out.println("Match found");
        }
        MatchResult res = matcher.toMatchResult();
        String matchedData = res.group();
        System.out.println(matchedData);
    }
}

Kết quả

Nhập văn bản: This is a sample Text, 123
Match found
This is a sample Text, 123

Các phương thức MatchResult khác

  • group(int group) - group cụ thể
  • groupCount() - số groups
  • start(), end() - vị trí match
  • start(int group), end(int group) - vị trí group