Validate Phone with Java Regular Expressions


In order to match the phone using regular expression, we use the matches method in Java. The java.lang.String.matches() method returns a boolean value which depends on the matching of the String with the regular expression.

Declaration − The java.lang.String.matches() method is declared as follows −

public boolean matches(String regex)

Let us see a program to validate a phone number with regular expressions −

Example

 Live Demo

public class Example {
   public static void main( String[] args ) {
      System.out.println(phone("+91 1023456789"));
   }
   // validate zip
   public static boolean phone( String z ) {
      return z.matches("\+[0-9]*\s+\d{10}" );
      // taking an assumption that a phone number is of ten digits
   }
}

Output

true

Updated on: 25-Jun-2020

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements