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

Cấu trúc \d trong Regular Expression Java

Phần biểu thức/metaký tự “\d” khớp với các chữ số (digits).

Ví dụ 1

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\d 24";
        String input = "This is sample text 12 24 56 89 24";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int count = 0;
        while (m.find()) {
            count++;
        }
        System.out.println("Số lần khớp: " + count);
    }
}

Kết quả

Số lần khớp: 2

Ví dụ 2

Chương trình Java sau đọc số 10 chữ số từ người dùng.

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

public class Test {
    public static void main(String args[]) {
        String regex = "\\d{10}";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập số điện thoại (10 chữ số): ");
        String input = sc.nextLine();
        
        // Tạo đối tượng Pattern
        Pattern p = Pattern.compile(regex);
        
        // Tạo đối tượng Matcher
        Matcher m = p.matcher(input);
        if (m.find()) {
            System.out.println("OK");
        } else {
            System.out.println("Đầu vào sai");
        }
    }
}

Kết quả 1

Nhập số điện thoại (10 chữ số): 9848022338
OK

Kết quả 2

Nhập số điện thoại (10 chữ số): 545
Đầu vào sai