Phone Number validation using Java Regular Expressions


The phone number can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the phone number and the given input phone number and returns true if they match and false otherwise.

Note: We are considering a demo number for our example since we cannot use our phone number publicly.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      String phoneNumber = "9999999998";
      String regex = "(0/91)?[7-9][0-9]{9}";
      System.out.println("The phone number is: " + phoneNumber);
      System.out.println("Is the above phone number valid? " + phoneNumber.matches(regex));
   }
}

Output

The phone number is: 9999999998
Is the above phone number valid? True

Now let us understand the above program.

The phone number is printed. The Pattern.matches() method matches the regular expression for the phone number and the given input phone number and the result is printed. A code snippet which demonstrates this is as follows:

String phoneNumber = "9999999998";
String regex = "(0/91)?[7-9][0-9]{9}";

System.out.println("The phone number is: " + phoneNumber);
System.out.println("Is the above phone number valid? " + phoneNumber.matches(regex));

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements