Search code examples
javaregexphone-number

Validate US phone number using Regular Expression


In my android project,I need to validate the mobile number that user has entered.The mobile number could be formatted like (456)123-1234.Always first character of the mobile number must be 4 or 5 or 6.I tried this regular expression.But it was failed.This the regular expression I tried.

"\\([4-6]{1}[0-9]{2}\\)[0-9]{3}\\-[0-9]{4}$";

Can anyone help me!Thanks in Advance!

I solved this problem by using this regular expression:

PHONE_REGEX ="\\([4-6]{1}[0-9]{2}\\) [0-9]{3}\\-[0-9]{4}$";

Solution

  •  String sPhoneNumber = "456-8889999";
    
    
      Pattern pattern = Pattern.compile("\\([4-6]{1}[0-9]{2}\\) [0-9]{3}\\-[0-9]{4}$");
      Matcher matcher = pattern.matcher(sPhoneNumber);
    
      if (matcher.matches()) {
          System.out.println("Phone Number Valid");
      }
      else
      {
          System.out.println("Phone Number must be in the form XXX-XXXXXXX");
      }