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

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


Flag này bật chế độ dòng Unix. Trong chế độ này, chỉ '\n' được dùng làm kết thúc dòng và '\r' được coi là ký tự thường (literal).

Ví dụ 1: Với UNIX_LINES flag

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\r"
                + "This is the second line\r"
                + "This is the third line\r";
        
        // Regex: dòng bắt đầu bằng T, kết thúc bằng e
        String regex = "^T.*e";
        
        // Biên dịch với UNIX_LINES
        Pattern pattern = Pattern.compile(regex, Pattern.UNIX_LINES);
        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 is the first line
This is the second line
This is the third line
Số khớp: 3

Trong chế độ bình thường, \r được coi là carriage-return (kết thúc dòng).

Ví dụ 2: Không dùng UNIX_LINES (mặc định)

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\r"
                + "This is the second line\r"
                + "This is the third line\r";
        
        String regex = "^T.*e";
        Pattern pattern = Pattern.compile(regex); // Không có flag
        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 is the first line
Số khớp: 1

Giải thích: Mặc định Java dùng \n làm line terminator. Với UNIX_LINES, \r không còn là line terminator, nên ^ và $ khớp ở ranh giả \n, khiến toàn bộ chuỗi (chỉ có \r) được coi là 1 dòng.