English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java regular expression's "\d" construction

Subexpression/Meta character " \ d " matching numbers.

example1

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);
   }
}

Output result

Number of matches: 2

example2

The following is an example of reading10Java program for counting digits.

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();
      //Create a Pattern object
      Pattern p = Pattern.compile(regex);
      //Create a Matcher object
      Matcher m = p.matcher(input);
      if(m.find()) {
         System.out.println("OK");
      } else {
         System.out.println("Wrong input");
      }
   }
}

Output1

Enter your phone number (10 digits):
9848022338
OK

Output2

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