【发布时间】:2016-10-05 15:42:41
【问题描述】:
我有一个来自任何国家的电话号码列表(字符串)。
例如:
var items = new List<string> { "+989302794433", "009891234599882", "+391234567890", "00336615551212"};
起初,我认为每个国家/地区代码长度恰好是两个数字,例如(33:法国,39:意大利,98:伊朗,...)。
使用 libphonenumber 库,您必须通过 regCode 进行解析。并且因为(在我的场景中)我得到了字符串列表(手机号码),那么我必须将国家代码与号码分开。
foreach (var item in items)
{
int countryCode = 0;
var number = "";
if (item.StartsWith("+"))
{
countryCode = int.Parse(item.Substring(1, 2));
number = item.Substring(3);
}
else if (item.StartsWith("00"))
{
countryCode = int.Parse(item.Substring(2, 2));
number = item.Substring(4);
}
var regCode = phoneUtil.GetRegionCodeForCountryCode(countryCode);
var numberWithRegCode = phoneUtil.Parse(number, regCode);
if (!phoneUtil.IsValidNumber(numberWithRegCode)) continue;
//else ...
}
此代码仅适用于长度为两个数字的国家/地区代码!
但过了一会儿,我知道有些国家代码长度是一个数字(例如,美国:1),甚至是三个数字!。
现在,是否存在使用 libphonenumber 库(或其他解决方案)来解决此问题的任何方式?
非常感谢
【问题讨论】:
-
这是题外话,因为您正在请求场外资源。此外,始终验证电话号码格式的理由可能有限。如果用户不想提供真实的电话号码,他们只会编一个。
-
您问题的第一部分很容易证明不正确 - 大多数国家/地区使用 3 位拨号代码,有些使用 4、5 甚至 6:en.wikipedia.org/wiki/List_of_country_calling_codes
-
他们的 github 页面作为演示链接到该网站 libphonenumber.appspot.com 并且他们的演示说使用“ISO 3166-1 两个字母的国家代码”并在此处链接:iso.org/iso/english_country_names_and_code_elements。所以也许可以尝试使用那些 2 个字符的字母代码而不是 1-3 位数字代码。例如,尝试在美国使用
US而不是840。
标签: c# libphonenumber