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

Phương thức Pattern.toString() trong Java với ví dụ


Lớp Pattern của gói java.util.regex là biểu diễn đã biên dịch của biểu thức chính quy.

Phương thức toString() của lớp này trả về biểu diễn chuỗi của biểu thức chính quy dùng để biên dịch Pattern hiện tại.

Ví dụ 1: In regex đã compile

import java.util.Scanner;
import java.util.regex.Pattern;

public class Example {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập chuỗi đầu vào");
        String input = sc.nextLine();
        
        String regex = "(\\d)";
        Pattern pattern = Pattern.compile(regex);
        
        // In regex đã biên dịch
        System.out.println("Biểu thức chính quy đã biên dịch: " + pattern.toString());
        
        if (pattern.matcher(input).find())
            System.out.println("Chuỗi đã cho chứa chữ số");
        else
            System.out.println("Chuỗi đã cho không chứa chữ số");
    }
}

Kết quả

Nhập chuỗi đầu vào: This 7est contain5 di9its in place of certain charac7er5
Biểu thức chính quy đã biên dịch: (\d)
Chuỗi đã cho chứa chữ số

Ví dụ 2: Pattern với anchor $

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Example {
    public static void main(String args[]) {
        String regex = "Tutorialspoint$";
        String input = "Hi how are you welcome to Tutorialspoint";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(input);
        
        int count = 0;
        if (match.find())
            System.out.println("Tìm thấy khớp");
        else
            System.out.println("Không tìm thấy khớp");
        
        System.out.println("Biểu thức chính quy: " + pattern.toString());
    }
}

Kết quả

Tìm thấy khớp
Biểu thức chính quy: Tutorialspoint$

Ứng dụng: Dùng để logging, debug, hiển thị pattern cho người dùng, hoặc lưu trữ pattern đã compile.