本文介绍了匹配 E.164 格式电话号码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加一个匹配所有可能的有效 E.164 格式电话号码的正则表达式.

I need to add a regular expression that matches all possible valid E.164 formatted phone numbers.

这个正则表达式适用于北美电话号码,但我需要一些也适用于国际号码的东西:

This regex works fine for for North American phone numbers, but I need something that will work for international numbers as well:

^(+1|1)?([2-9]\d\d[2-9]\d{6})$

例如:+13172222222 匹配13172222222 仍然匹配,因为 +1 或 1 是可选的3172222222 仍然匹配,因为 +1 或 1 是可选的3171222222 不匹配并且不是有效的 NANPA 编号.

Example: +13172222222 matches 13172222222 still matches because +1 or 1 are optional 3172222222 still matches because +1 or 1 are optional 3171222222 does not match and is not a valid NANPA number.

来源:Freeswitch.org

我也遇到了这个相关问题,但我认为这对我的需求来说太疯狂了.就我而言,我只是验证黑名单的条目,并将其与传入的 Twilio 数据进行比较;所以,我不太关心国家代码有效的天气.我真的只需要测试一个数字是否与一般的 E.164 形式相匹配,而不是假设它是 NANPA.

I also came across this related question, but I think that it is way too crazy for my needs. In my case, I am simply validating an entry for a blacklist, which I'm comparing to incoming Twilio data; so, I care much less about weather a country code is valid. I really only need to test if a number matches the general E.164 form, rather than assuming it's a NANPA.

为了更好地理解我需要匹配的内容,这里是 Twilio 文档:

To be better understand what I need to match, here is an example from the Twilio Documentation:

请求中的所有电话号码来自Twilio 采用 E.164 格式,如果可能的.例如,(415) 555-4345将通过'+14155554345'.不过偶尔也会有这样的情况Twilio 无法标准化的地方来电显示到 E.164.在这些情况 Twilio 将报告原始数据来电显示字符串.

我想匹配 +14155554345 之类的东西,但不是 (415) 555-4345、415555434、555-4345 或 5554345.不过,正则表达式不应限制自己只匹配美国国家/地区代码.基本上,它应该匹配 +xxxxxxxxxxx 格式.我还认为这个数字可能更长,因为有多位国家代码,例如在英国.T-Mobile 的英国号码是 +447953966150,如果我能想出更好的例子,我会更新这个.

I want to match something like +14155554345, but not (415) 555-4345, 415555434, 555-4345 or 5554345. The regex should not restrict itself to only matching the US country code though. Basically, it should match the +xxxxxxxxxxx format. I also think the number could be longer, as there are multi-digit country codes, such as in the UK. T-Mobile's UK number is +447953966150 I'll update this if I can come up with a better example.

推荐答案

接受的答案是好的,除了 E.164 号码最多可以有 15 位数字.规范也没有指出最小值,所以我不一定指望 10.

The accepted answer is good, except an E.164 number can have up to 15 digits. The specification also doesn't indicate a minimum, so I wouldn't necessarily count on 10.

应该是^\+?[1-9]\d{1,14}$

参见 http://en.wikipedia.org/wiki/E.164

这篇关于匹配 E.164 格式电话号码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:05