如何使用正则表达式验证电话号码 [英] How to validate phone numbers using regex

查看:98
本文介绍了如何使用正则表达式验证电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用全面的正则表达式来验证电话号码.理想情况下,它将处理国际格式,但必须处理美国格式,包括以下内容:

I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:

  • 1-234-567-8901
  • 1-234-567-8901 x1234
  • 1-234-567-8901 ext1234
  • 1 (234) 567-8901
  • 1.234.567.8901
  • 1/234/567/8901
  • 12345678901
  • 1-234-567-8901
  • 1-234-567-8901 x1234
  • 1-234-567-8901 ext1234
  • 1 (234) 567-8901
  • 1.234.567.8901
  • 1/234/567/8901
  • 12345678901

我将用当前的尝试回答,但我希望有人能做得更好和/或更优雅.

I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.

推荐答案

更好的选择...仅去除输入中的所有非数字字符("x"和前导"+"符号除外),请注意英式英语当要求使用国际前缀时,倾向于以非标准格式+44 (0) ...写数字(在这种情况下,应完全丢弃(0)).

Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form +44 (0) ... when asked to use the international prefix (in that specific case, you should discard the (0) entirely).

然后,您得到的值如下:

Then, you end up with values like:

 12345678901
 12345678901x1234
 345678901x1234
 12344678901
 12345678901
 12345678901
 12345678901
 +4112345678
 +441234567890

然后,当您显示时,请重新格式化您的内心内容.例如

Then when you display, reformat to your hearts content. e.g.

  1 (234) 567-8901
  1 (234) 567-8901 x1234

这篇关于如何使用正则表达式验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆