Validate Phone with Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 08-Jan-2019 15:45:14
Advertisements