Validate phone number using java regular expression

In this example we are going to be validating any phone number. We are going to put following checks against any phone number under test.

  • The phone number should be 10 digit number.
  • Splitted by hi-fen(-) and the end result should look like xxx-xxx-xxxx

package com.amzi.xml;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhoneNumber {
 public static void main(String[] args) {

  String phNumber = "123-222-3333";
  //String phNumber = "123 123 1234";

  Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
  Matcher matcher = pattern.matcher(phNumber);

  if (matcher.matches()) {
   System.out.println("Phone Number is Valid");
  } else {
   .println("Phone Number isn't in this formate XXX-XXX-XXXX");

Phone Number is Valid


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India.
    or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.