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

Cách so khớp các chữ số bằng Java Regular Expression (RegEx)

Bạn có thể so khớp các chữ số trong một chuỗi nhất định bằng cách sử dụng ký tự meta " \\ d "hoặc bằng cách sử dụng biểu thức sau:

[0-9]

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 of digits: "+count);
   }
}

Đầu ra

Enter a String
sample text 1234 6657
Number of digits: 8

Ví dụ 2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //regular expression to accept 10 digits
      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("10 digit number");
      } else {
         System.out.println("wrong input");
      }
   }
}

Đầu ra 1

Enter input value:
9848022558
10 digit number

Đầu ra 2

Enter input value:
5337
wrong input