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

POSIX Character Class \p{InGreek} trong Java Regex


Khái niệm

\p{InGreek} khớp ký tự thuộc Unicode block Greek.

Ví dụ 1: Đếm ký tự Greek

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

public class Example1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập chuỗi: ");
        String input = sc.nextLine();
        String regex = "\\p{InGreek}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Số ký tự Greek: " + count);
    }
}
Nhập chuỗi: sample text αβ ηθ ξψ
Số ký tự Greek: 6

Ví dụ 2: Kiểm tra chuỗi có ký tự Greek

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập chuỗi: ");
        String input = sc.nextLine();
        String regex = "^.+\\p{InGreek}.+";
        boolean result = input.matches(regex);
        if (result) {
            System.out.println("Chuỗi chứa ký tự Greek");
        } else {
            System.out.println("Chuỗi không chứa ký tự Greek");
        }
    }
}
Nhập chuỗi: sample text αβ
Chuỗi chứa ký tự Greek

Các Unicode Block phổ biến

BlockRegex
Basic Latin\p{InBasicLatin}
Latin-1 Supplement\p{InLatin-1Supplement}
Greek\p{InGreek}
Cyrillic\p{InCyrillic}
Vietnamese (trong Latin Extended)\p{InLatinExtendedAdditional}
CJK Unified Ideographs\p{InCJKUnifiedIdeographs}