Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Regular Expression "d" construct in Java
The subexpression/metacharacter “\d” matches the digits.
Example 1
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
Number of matches: 2
Example 2
Following is a Java program that reads a 10-digit number from the user.
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();
//Creating a Pattern object
Pattern p = Pattern.compile(regex);
//Creating a Matcher object
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("OK");
} else {
System.out.println("Wrong input");
}
}
}
Output 1
Enter your phone number (10 digits): 9848022338 OK
Output 2
Enter your phone number (10 digits): 545 Wrong input
Advertisements
