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

How to use Java regular expression (RegEx) to match numbers?

You can use the metacharacter " \\d Use the following expression to match numbers in the given string: 

[0-9]

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Read a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\d";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of digits: ");+count);
   }
}

Output Result

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

Example2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //Accept10Regular expression for a digit number
      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");
      }
   }
}

Output1

Enter input value:
9848022558
10 digit number

Output2

Enter input value:
5337
wrong input