简体   繁体   English

使用正则表达式验证美国电话号码

[英]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. 在我的android项目中,我需要验证用户输入的手机号码。手机号码的格式可以是(456)123-1234。总是手机号码的第一个字符必须为4或5或6。表达式。但是失败了。这是我尝试过的正则表达式。

"\\([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}$";

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 http://regex101.com/r/pZ7aL4

If you wanted to allow to an optional space after the closing parenthesis, ie: 如果要在右括号后留一个可选的空间,即:

(456) 123-1234 (456)123-1234

You would modify regex slightly like this: 您可以像这样稍微修改正则表达式:

^\([4-6]{1}[0-9]{2}\)\s?[0-9]{3}-[0-9]{4}$
 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");
  }

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. 如果您使用此正则表达式阻止去往长途号码的呼出电话,则需要特定的白名单或黑名单-如果您依赖正则表达式,则可能会有一些昂贵的惊喜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM