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

Trường Pattern.LITERAL trong Java với ví dụ


Flag này bật phân tích literal (chữ diện) của pattern. Trong chế độ này, tất cả ký tự bao gồm escape sequences và metacharacters không có ý nghĩa đặc biệt, được coi như ký tự thường.

Ví dụ, bình thường regex "^This" khớp các dòng bắt đầu bằng từ "This".

Ví dụ 1: Chế độ LITERAL

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

public class LTERAL_Example {
    public static void main(String[] args) {
        String input = "This is the first line\n"
                + "This is the second line\n"
                + "^This is the third line";
        
        String regex = "^This";
        
        // Biên dịch với LITERAL flag
        Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
        Matcher matcher = pattern.matcher(input);
        
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println(matcher.group());
        }
        System.out.println("Số khớp: " + count);
    }
}

Kết quả

^This
Số khớp: 1

Trong chế độ literal, metacharacter "^" không có ý nghĩa và regex "^This" khớp chính xác từ "^This".

Ví dụ 2: So sánh in ra chuỗi gốc

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

public class LTERAL_Example {
    public static void main(String[] args) {
        String input = "This is the first line\n"
                + "This is the second line\n"
                + "^This is the third line";
        
        String regex = "^This";
        Pattern pattern = Pattern.compile(regex, Pattern.LITERAL);
        
        System.out.println("Chuỗi gốc in thường: \n" + input);
        
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.println(matcher.group());
        }
        System.out.println("Số khớp: " + count);
    }
}

Kết quả

Chuỗi gốc in thường:
This is the first line
This is the second line
^This is the third line
^This
Số khớp: 1

Ứng dụng: Dùng khi cần tìm kiếm chuỗi cố định chứa nhiều metacharacter (như đường dẫn file, regex literal) mà không muốn escape thủ công.