Extract code country from phone number [libphonenumber]

前端 未结 7 1740
情深已故
情深已故 2020-11-27 13:21

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 a

相关标签:
7条回答
  • 2020-11-27 13:36

    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) {
                ""
            }
        }
    
    0 讨论(0)
  • 2020-11-27 13:36

    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/WpfWindowsLib/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

    0 讨论(0)
  • 2020-11-27 13:40

    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.

    0 讨论(0)
  • 2020-11-27 13:44

    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

    0 讨论(0)
  • 2020-11-27 13:51

    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.

    0 讨论(0)
  • 2020-11-27 13:54

    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());
    }
    
    0 讨论(0)
提交回复
热议问题