Question

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}$";
Was it helpful?

Solution 2

 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");
  }

OTHER TIPS

A regex to match your format:

(456)123-1234  (starting with only 4,5 or 6)

Would be:

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

Example:

http://regex101.com/r/pZ7aL4

If you wanted to allow to an optional space after the closing parenthesis, ie:

(456) 123-1234

You would modify regex slightly like this:

^\([4-6]{1}[0-9]{2}\)\s?[0-9]{3}-[0-9]{4}$

You should be aware that there are area codes in north america that share the US format as part of the North American Numbering Plan, but do not share the rate structure with US telephone carriers. Examples include Puerto Rico, the Dominican republic, Canada, etc.

If you're using this regex to block outbound calls to or from long-distance numbers, you need a specific whitelist or blacklist -- if you rely on regex, you could have some expensive surprises.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top