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

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


Trường DOTALL của lớp Pattern bật chế độ dotall. Mặc định, metacharacter "." trong regex khớp với tất cả ký tự trừ line terminators (\n, \r, v.v.).

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

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

public class DOTALL_Example {
    public static void main(String args[]) {
        String regex = ".";
        String input = "this is a sample \nthis is second line";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.print(matcher.group());
        }
        System.out.println();
        System.out.println("Số ký tự khớp (kể cả newline?): " + count);
    }
}

Kết quả

this is a sample this is second line
Số ký tự khớp (kể cả newline?): 36

Chấm . không khớp ký tự newline \n, nên count = 36 (bỏ qua 1 newline).

Ví dụ 2: Có dùng DOTALL

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

public class DOTALL_Example {
    public static void main(String args[]) {
        String regex = ".";
        String input = "this is a sample \nthis is second line";
        
        Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        Matcher matcher = pattern.matcher(input);
        
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.print(matcher.group());
        }
        System.out.println();
        System.out.println("Số ký tự khớp (kể cả newline): " + count);
    }
}

Kết quả

this is a sample this is second line
Số ký tự khớp (kể cả newline): 37

Với DOTALL, . khớp cả newline, count = 37 (36 ký tự + 1 newline).

Lưu ý: Flag này cũng có thể viết là (?s) trong regex: Pattern.compile("(?s).").