我试图把一个全面的正则表达式放在一起来验证电话号码。理想情况下,它可以处理国际格式,但它必须处理美国格式,包括以下内容:
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
我会用我目前的尝试来回答,但我希望有人有更好的和/或更优雅的东西。
当前回答
简单的正则表达式和其他技巧都有用。
.*
但是显示输入的提示/示例/占位符/工具提示。
然后在提交之前在前端验证格式是否正确是最好的体验。
这将为没有经验的用户简化格式。
其他回答
我在另一个SO问题上回答了这个问题,然后决定把我的答案也包括在这个线程上,因为没有人解决如何要求/不要求项目,只是分发正则表达式: 正则表达式工作错误,匹配意想不到的东西
从我在那个网站上的帖子中,我创建了一个快速指南,帮助任何人为自己想要的电话号码格式制作自己的正则表达式,我要警告(就像我在另一个网站上所做的那样),如果你限制太多,你可能不会得到想要的结果,并且没有“一宜之计”的解决方案来接受世界上所有可能的电话号码——只有你决定接受的格式作为你选择的格式。使用风险自负。
快速小抄
Start the expression: /^ If you want to require a space, use: [\s] or \s If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing. If you want anything to be optional, put a ? after it If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \- If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot. \d{3} : Requires a 3-digit number: 000-999. Shorthand for [0-9][0-9][0-9]. [2-9] : Requires a digit 2-9 for that slot. (\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped. If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. (?:77|78) or [77|78] will require 77 or 78. $/ : End the expression
我也在为同样的问题而挣扎,试图让我的应用程序经得起未来的考验,但这些人让我走上了正确的方向。我实际上并不是在检查数字本身,看它是否有效,我只是试图确保输入的一系列数字可能有或没有扩展名。
最坏的情况是,如果用户必须从XML文件中提取一个未格式化的数字,他们仍然只是将数字输入到手机的数字pad 012345678x5中,没有真正的理由保持它的美观。这种RegEx对我来说是这样的:
\d+ ?\w{0,9} ?\d+
01234467分机号123456 01234567 x123456 01234567890
使用简单的正则表达式处理各种国际电话号码几乎是不可能的。
你最好使用numverify.com这样的服务,他们为国际电话号码验证提供了免费的JSON API,此外,每个请求都可以获得有关国家、位置、运营商和线路类型的有用详细信息。
/\b(\d{3}[^\d]{0,2}\d{3}[^\d]{0,2}\d{4})\b/
这是我目前为止最好的尝试。它处理上面的格式,但我确信我错过了一些其他可能的格式。
^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$