我有一个像这样的字符串:+33123456789(法国电话号码)。我想在不知道国家的情况下提取国家代码(+33)。例如,如果我有另一个国家的电话,它应该可以工作。我使用Google图书馆https://code.google.com/p/libphonenumber/。
如果我知道国家/地区,这很酷,我可以找到国家/地区代码:
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
int countryCode = phoneUtil.getCountryCodeForRegion(locale.getCountry());
但是我不知道如何在不了解国家的情况下解析字符串。
最佳答案
好的,所以我加入了libphonenumber(https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss)的Google小组,并提出了一个问题。
如果我的电话号码以“+”开头,则无需在参数中设置国家/地区。这是一个例子:
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());
}