Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

คอนสตรัคต์ \d ในนิพจน์ปกติ Java

ซับนิพจน์/เมตาอักขระ “\d” จับคู่ตัวเลข (digits)

ตัวอย่างที่ 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("Number of matches: " + count); 
    } 
}

ผลลัพธ์

Number of matches: 2

ตัวอย่างที่ 2

โปรแกรม Java ต่อไปนี้อ่านหมายเลข 10 หลักจากผู้ใช้

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("Enter your phone number (10 digits): "); 
        String input = sc.nextLine(); 
        // สร้างออบเจ็กต์ Pattern 
        Pattern p = Pattern.compile(regex); 
        // สร้างออบเจ็กต์ Matcher 
        Matcher m = p.matcher(input); 
        if(m.find()) { 
            System.out.println("OK"); 
        } else { 
            System.out.println("Wrong input"); 
        } 
    } 
}

ผลลัพธ์ที่ 1

Enter your phone number (10 digits): 9848022338 
OK

ผลลัพธ์ที่ 2

Enter your phone number (10 digits): 545 
Wrong input