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

วิธีจับคู่ตัวอักษรที่ไม่ใช่ตัวเลขด้วย Java Regular Expression (RegEx)

คุณสามารถจับคู่ตัวอักษรที่ไม่ใช่ตัวเลขได้โดยใช้เมตาอักขระ "\\D"

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

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class Example { 
    public static void main(String args[]) { 
        // อ่านสตริงจากผู้ใช้ 
        System.out.println("Enter a String"); 
        Scanner sc = new Scanner(System.in); 
        String input = sc.nextLine(); 
        String regex = "\\D"; 
        // คอมไพล์นิพจน์ปกติ 
        Pattern pattern = Pattern.compile(regex); 
        // ดึงออบเจ็กต์ matcher 
        Matcher matcher = pattern.matcher(input); 
        int count = 0; 
        while(matcher.find()) { 
            count++; 
        } 
        System.out.println("Number non-digit characters: " + count); 
    } 
}

ผลลัพธ์

Enter a String sample text 2425 36 
Number non-digit characters: 13

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

import java.util.Scanner; 
public class RegexExample { 
    public static void main( String args[] ) { 
        // นิพจน์ปกติยอมรับคำ 10 ตัวอักษร 
        String regex = "\\D{10}"; 
        System.out.println("Enter input value: "); 
        Scanner sc = new Scanner(System.in); 
        String input = sc.nextLine(); 
        boolean result = input.matches(regex); 
        if(result) { 
            System.out.println("input matched"); 
        } else { 
            System.out.println("wrong input"); 
        } 
    } 
}

ผลลัพธ์ที่ 1

Enter input value: sample abc 
input matched

ผลลัพธ์ที่ 2

Enter input value: sample1234 
wrong input