我有一个带有国家代码的手机号码列表,例如“919638095998”号码。我已经提到了 libphonenumber google example同样,但首先我们需要传递国家 2 位代码,我最初不知道。那么我怎么知道这个号码来自哪个国家呢?
我也有一个解决方案,就是手动从手机号码中一位一位地提取代码,然后与国家代码进行比较。但这是一项长期的任务,它也会给我带来糟糕的表现。谁能提出合适的解决方案?
最佳答案
libphonenumber为你做那件事。您所要做的就是在您的电话号码前添加 +
符号,并在解析电话号码时省略国家代码。
String numberStr = "+919638095998";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
Phonenumber.PhoneNumber numberProto = phoneUtil.parse(numberStr, "");
System.out.println("Country code: " + numberProto.getCountryCode());
//This prints "Country code: 91"
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
关于java - 从手机号码中提取国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12259347/