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

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


Trường CASE_INSENSITIVE của lớp Pattern khớp ký tự không phân biệt chữ hoa/thường. Khi dùng flag này trong compile() và tìm kiếm ký tự bằng regex, cả hai trường hợp (hoa/thường) đều khớp.

Lưu ý – Mặc định, flag này chỉ khớp ký tự ASCII.

Ví dụ 1: Đếm ký tự 't'/'T' trong văn bản

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

public class CASE_INSENSITIVE_Example {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập dữ liệu đầu vào: ");
        String input = sc.nextLine();
        System.out.println("Nhập ký tự cần tìm: ");
        char ch = sc.next().toCharArray()[0];
        
        // Regex: ký tự ch
        String regex = "[" + ch + "]";
        
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);
        
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Ký tự '" + ch + "' xuất hiện " + count + " lần (không phân biệt hoa/thường)");
    }
}

Kết quả

Nhập dữ liệu đầu vào: Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
Nhập ký tự cần tìm: T
Ký tự 'T' xuất hiện 20 lần (không phân biệt hoa/thường)

Ví dụ 2: Kiểm tra boolean string (true/false không phân biệt hoa/thường)

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

public class VerifyBoolean {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập giá trị chuỗi: ");
        String str = sc.next();
        
        Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        
        if (matcher.matches()) {
            System.out.println("Chuỗi đã cho là kiểu boolean");
        } else {
            System.out.println("Chuỗi đã cho không phải kiểu boolean");
        }
    }
}

Kết quả 1

Nhập giá trị chuỗi: true
Chuỗi đã cho là kiểu boolean

Kết quả 2

Nhập giá trị chuỗi: false
Chuỗi đã cho là kiểu boolean

Kết quả 3

Nhập giá trị chuỗi: hello
Chuỗi đã cho không phải kiểu boolean

Mẹo: Dùng (?i) inline flag: Pattern.compile("(?i)true|false").