从电话号码[libphonenumber]中提取代码国家/地区

mrr*_*aat 71 android libphonenumber

我有一个这样的字符串:+33123456789(法国电话号码).我想在不知道国家的情况下提取国家代码(+33).例如,如果我有来自其他国家的另一部电话,它应该可以工作.我使用谷歌库https://code.google.com/p/libphonenumber/.

如果我知道这个国家,很酷我可以找到国家代码:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
int countryCode = phoneUtil.getCountryCodeForRegion(locale.getCountry());
Run Code Online (Sandbox Code Playgroud)

但我找不到解析字符串而不知道国家的方法.

mrr*_*aat 114

好的,所以我加入了libphonenumber的谷歌小组(https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss),我问了一个问题.

如果我的电话号码以"+"开头,则无需在参数中设置国家/地区.这是一个例子:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    // phone must begin with '+'
    PhoneNumber numberProto = phoneUtil.parse(phone, "");
    int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}
Run Code Online (Sandbox Code Playgroud)

  • 这个wackadoo疯狂图书馆令人惊叹,比Android中包含的PhoneNumberUtil`s库好十亿倍 (4认同)
  • @Schweta defaultRegion参数应为null:defaultRegion - ISO 3166-1双字母区域代码,表示我们期望该数字来自的区域.仅在被解析的数字不是以国际格式编写时才使用.在这种情况下,数字的country_code将被存储为所提供的默认区域的country_code.如果保证数字以"+"开头,后跟国家/地区呼叫代码,则可以提供"ZZ"或null. (3认同)