Extract code country from phone number [libphonenumber]
Asked Answered
T

7

98

I have a string like this : +33123456789 (french phone number). I want to extract the country code (+33) without knowing the country. For example, it should work if i have another phone from another country. I use the google library https://code.google.com/p/libphonenumber/.

If I know the country, it is cool I can find the country code :

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
int countryCode = phoneUtil.getCountryCodeForRegion(locale.getCountry());

but I don't find a way to parse a string without to know the country.

Thy answered 29/5, 2013 at 8:55 Comment(4)
possible duplicate of Getting telephone country code with AndroidSuspender
See also #2530877Suspender
The first link is based on telephone country code. But in my case, I can have a string which is a french phone number with an english phone. So if i retrieve the current locale, i will have "EN" but my string will be a french country codeThy
@Simon, I realize this is an old post, but I don't think the two questions you noted are duplicates. Cheers.Hornpipe
T
150

Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.

I don't need to set the country in parameter if my phone number begins with "+". Here is an example :

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());
}
Thy answered 30/5, 2013 at 11:46 Comment(8)
this wackadoo crazy library is amazing and is a billion times better than the included PhoneNumberUtils library in androidLunarian
@aat would you tell me how it will work without using countryISOCode in ( phoneUtil.parse(phone, "");) your answer, please respondZins
@Shweta If you have a question, please post it on a new thread on SOThy
@aat ok, but your answer is not correct, without giving any countryISOCode this code won't executeZins
@Schweta defaultRegion parameter should be null: defaultRegion - the ISO 3166-1 two-letter region code that denotes the region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.Folie
What should I do if I need to parse a phone number from my phonebook to E164 format and the locale of the phone might change (e.g. when the user of a phone travels to other country). I also know that most numbers are not written in format +.....Heritable
@Lunarian PhoneNumberUtils internal uses same lib :DCaligula
Is it possible to get the E164 number from numbers in the phone book? Most users won't save contacts to include the country ISO.Liponis
T
4

I have got kept a handy helper method to take care of this based on one answer posted above:

Imports:

import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil

Function:

    fun parseCountryCode( phoneNumberStr: String?): String {
        val phoneUtil = PhoneNumberUtil.getInstance()
        return try {
            // phone must begin with '+'
            val numberProto = phoneUtil.parse(phoneNumberStr, "")
            numberProto.countryCode.toString()
        } catch (e: NumberParseException) {
            ""
        }
    }
Transfinite answered 2/7, 2019 at 13:52 Comment(0)
J
3

In here you can save the phone number as international formatted phone number

internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);

it return the phone number as International format +94 71 560 4888

so now I have get country code as this

String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();

Hope this will help you

Jourdain answered 30/5, 2013 at 7:55 Comment(5)
what is internationalFormatPhoneNumber DataType and phoneUtilNuke
the givenPhoneNumber parameter is not a string, it must be an already parsed phone number in witch you need the default region to generateSkyscraper
@GilSH yes givenPhoneNumber not String, It is PhoneNumber object.Jourdain
what is givenPhoneNumber??Lauralee
This depends on a space existing between the country code and the rest of the phone number. It won't be able to handle the string "+94715604888"Devon
A
1

Here is a solution to get the country based on an international phone number without using the Google library.

Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:

1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada

Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.

For my code, I defined a class which holds information for ever digit:

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:

country code 1: byPhone[1].Country is US  
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada  
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since   
                   byPhone[1].Country is US, also 1235 is US, because no other   
                   country was found in the later digits

Here is the method which returns the country based on the phone number:

/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
  if (phoneNumber.Length==0) return null;

  var isFirstDigit = true;
  DigitInfo? digitInfo = null;
  Country? country = null;
  foreach (var digitChar in phoneNumber) {
    var digitIndex = digitChar - '0';
    if (isFirstDigit) {
      isFirstDigit = false;
      digitInfo = ByPhone[digitIndex];
    } else {
      if (digitInfo!.Digits is null) return country;

      digitInfo = digitInfo.Digits[digitIndex];
    }
    if (digitInfo is null) return country;

    country = digitInfo.Country??country;
  }
  return country;
}

The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github: https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsHelperLib/CountryCode.cs

The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail

Change 23.1.23: I moved CountryCode.cs to WpfWindowsHelperLib, which doesn't have any WPF dependencies, despite it's name.

Assr answered 11/4, 2020 at 13:14 Comment(2)
git link doesn't work for meInfusorian
Sorry, I moved it to a different library in the same solution to remove any dependency from WPF.Assr
C
0

Use a try catch block like below:

try { 

const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);

}catch(e){}
Cottonseed answered 10/4, 2020 at 13:12 Comment(0)
K
-7

If the string containing the phone number will always start this way (+33 or another country code) you should use regex to parse and get the country code and then use the library to get the country associated to the number.

Khelat answered 29/5, 2013 at 9:17 Comment(1)
It exists a lot of different country code : http://en.wikipedia.org/wiki/List_of_country_calling_codesThy
C
-29

Here's a an answer how to find country calling code without using third-party libraries (as real developer does):

Get list of all available country codes, Wikipedia can help here: https://en.wikipedia.org/wiki/List_of_country_calling_codes

Parse data in a tree structure where each digit is a branch.

Traverse your tree digit by digit until you are at the last branch - that's your country code.

Cubature answered 12/7, 2016 at 15:27 Comment(4)
I'm down-voting this because of this comment: "Here's a an answer how to find country calling code without using third-party libraries (as real developer does):" Why do you think software makes progress? It is because people do not have to re-invent the wheel every time. A REAL developer uses third-party libraries because he/she is smart.Blitzkrieg
Your personal opinion does not make my answer incorrect, does it? In fact, this is the only correct and bullet-proof answer so far... and yes, it does not require any 3rd party software in order to work. You're welcome to buy my solution if you insist on using 3rd party libraries.Cubature
Updating a library is easier than continually going to a Wikipedia page to check to see if the list of country calling codes has changed.Devon
Downvotes are not for the technical content but for the very unnecessary claim "as real developer does". It is even grammatically incorrect. Hard to grasp why author would not remove this.Extemporaneous

© 2022 - 2024 — McMap. All rights reserved.