Computer >> Máy Tính >  >> Lập trình >> Java

Cách đối sánh các chữ số không bằng cách sử dụng Biểu thức chính quy Java (RegEx)

Bạn có thể đối sánh ký tự không phải chữ số bằng cách sử dụng ký tự meta " \\ D" .

Ví 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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\D";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number non-digit characters: "+count);
   }
}

Đầu ra

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

Ví dụ 2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //regular expression to accept 5 letter word
      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");
      }
   }
}

Đầu ra 1

Enter input value:
sample abc
input matched

Đầu ra 2

Enter input value:
sample1234
wrong input