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.

Homam
  • 5,018
  • 4
  • 36
  • 39
mrroboaat
  • 5,602
  • 7
  • 37
  • 65
  • possible duplicate of [Getting telephone country code with Android](http://stackoverflow.com/questions/5402253/getting-telephone-country-code-with-android) – Simon May 29 '13 at 09:18
  • See also http://stackoverflow.com/questions/2530377/list-of-phone-number-country-codes – Simon May 29 '13 at 09:18
  • 1
    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 code – mrroboaat May 29 '13 at 09:34
  • @Simon, I realize this is an old post, but I don't think the two questions you noted are duplicates. Cheers. – Bink Dec 20 '21 at 22:13

7 Answers7

149

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());
}
Sandor Drieënhuizen
  • 6,310
  • 5
  • 37
  • 80
mrroboaat
  • 5,602
  • 7
  • 37
  • 65
  • 7
    this wackadoo crazy library is amazing and is a billion times better than the included PhoneNumberUtil`s` library in android – Aphex Oct 23 '14 at 08:46
  • @aat would you tell me how it will work without using countryISOCode in ( phoneUtil.parse(phone, "");) your answer, please respond – Ash Nov 04 '14 at 16:47
  • 1
    @Shweta If you have a question, please post it on a new thread on SO – mrroboaat Nov 04 '14 at 16:50
  • 1
    @aat ok, but your answer is not correct, without giving any countryISOCode this code won't execute – Ash Nov 05 '14 at 12:01
  • 4
    @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. – xnagyg Jan 15 '15 at 12:29
  • 1
    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 +..... – user2924714 Nov 01 '16 at 16:02
  • @Aphex PhoneNumberUtils internal uses same lib :D – CoDe Nov 03 '17 at 10:18
  • 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. – Victor Okech Apr 27 '22 at 08:17
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) {
            ""
        }
    }
Ali Nawaz
  • 2,016
  • 20
  • 30
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

Thilina Rubasingha
  • 1,049
  • 1
  • 9
  • 17
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.

Peter Huber
  • 3,052
  • 2
  • 30
  • 42
0

Use a try catch block like below:

try { 

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

}catch(e){}
stealthyninja
  • 10,343
  • 11
  • 51
  • 59
soni kumari
  • 313
  • 4
  • 4
-6

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.

yjajkiew
  • 47
  • 5
  • It exists a lot of different country code : [http://en.wikipedia.org/wiki/List_of_country_calling_codes](http://en.wikipedia.org/wiki/List_of_country_calling_codes) – mrroboaat May 29 '13 at 09:24
-26

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.

Unobic
  • 47
  • 2
  • 38
    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. – Carl B Sep 05 '16 at 08:55
  • 2
    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. – Unobic Jun 20 '17 at 13:46
  • 2
    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. – Flimm Nov 22 '18 at 12:28
  • 1
    @Unobic Sorry man. They shouldn't vote because of personal opinion on Stackoverflow. I was looking exactly for your answer when searching. So thanks from me. Have my upvote at least. – Ybrin Feb 05 '20 at 00:27