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

POSIX Character Class \p{Sc} trong Java Regex


Khái niệm

\p{Sc} (Symbol Currency) khớp các ký hiệu tiền tệ: $, €, £, ¥, ₹, ₫...

Ví dụ 1: Đếm ký hiệu tiền tệ

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{Sc}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Số ký hiệu tiền tệ: " + count);
    }
}
Nhập chuỗi: euro €, pounds £, dollar $, yen ¥
Số ký hiệu tiền tệ: 4

Ví dụ 2: Lọc chuỗi chứa tiền tệ

String regex = "^.*\\p{Sc}.*$";
// Input: # #$$@ £shelling -> khớp (có $ và £)
// Input: hello sample 243test -> không khớp

Các ký hiệu tiền tệ phổ biến

Ký hiệuTênUnicode
$DollarU+0024
€EuroU+20AC
£PoundU+00A3
¥Yen/YuanU+00A5
₹RupeeU+20B9
₫DongU+20AB