[android] 전화 번호 [libphonenumber]에서 코드 국가 추출

다음과 같은 문자열이 있습니다. +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=ko&fromgroups#!forum/libphonenumber-discuss )에 가입했고 질문을했습니다.

전화 번호가 “+”로 시작하면 매개 변수에서 국가를 설정할 필요가 없습니다. 다음은 예입니다.

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());
}


답변

여기에서 전화 번호를 국제 형식의 전화 번호로 저장할 수 있습니다.

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

국제 형식으로 전화 번호를 반환합니다. +94 71560 4888

그래서 이제 국가 코드를 얻었습니다.

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

이것이 당신을 도울 수 있기를 바랍니다


답변

위에 게시 된 한 가지 답변을 기반으로이 문제를 처리하는 편리한 도우미 메서드를 유지했습니다.

수입품 :

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

함수:

    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) {
            ""
        }
    }


답변

아래와 같이 try catch 블록을 사용하십시오.

try {

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

}catch(e){}


답변

다음은 Google 라이브러리를 사용하지 않고 국제 전화 번호로 국가를 가져 오는 솔루션입니다.

먼저 나라를 파악하는 것이 왜 그렇게 어려운지 설명하겠습니다. 소수 국가의 국가 코드는 1 자리, 2, 3 또는 4 자리입니다. 그것은 충분히 간단합니다. 그러나 국가 코드 1은 미국뿐만 아니라 캐나다 및 일부 소규모 지역에도 사용됩니다.

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

숫자 2..4는 그것이 미국인지 캐나다인지를 결정합니다. 첫 번째 xxx는 캐나다이고 나머지는 미국인 것처럼 국가를 알아내는 쉬운 방법은 없습니다.

내 코드의 경우 숫자에 대한 정보를 보유하는 클래스를 정의했습니다.

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

첫 번째 배열은 숫자의 첫 번째 숫자에 대한 DigitInfo를 보유합니다. 두 번째 숫자는 DigitInfo.Digits에 대한 인덱스로 사용됩니다. 하나는 Digits가 비어있을 때까지 해당 Digits 체인 아래로 이동합니다. Country가 정의 된 경우 (즉, null이 아님) 해당 값이 반환되고, 그렇지 않으면 이전에 정의 된 모든 국가가 반환됩니다.

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

전화 번호를 기준으로 국가를 반환하는 방법은 다음과 같습니다.

/// <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;
}

나머지 코드 (전 세계 모든 국가에 대한 DigitInfos, 테스트 코드 등)는 너무 커서 여기에 게시 할 수 없지만 Github에서 찾을 수 있습니다.
https://github.com/PeterHuberSg/WpfWindowsLib/blob /master/WpfWindowsLib/CountryCode.cs

코드는 WPF TextBox의 일부이며 라이브러리에는 이메일 주소 등에 대한 다른 컨트롤도 포함되어 있습니다. 자세한 설명은 CodeProject에 있습니다. 국제 전화 번호 유효성 검사는 자세히 설명합니다.


답변

전화 번호가 포함 된 문자열이 항상이 방법으로 시작하는 경우 (+33 또는 다른 국가 코드) 정규식을 사용하여 국가 코드를 구문 분석하고 가져온 다음 라이브러리를 사용하여 번호에 연결된 국가를 가져와야합니다.


답변

다음은 타사 라이브러리를 사용하지 않고 국가 전화 코드를 찾는 방법입니다 (실제 개발자처럼).

사용 가능한 모든 국가 코드 목록을 얻으십시오. Wikipedia는 여기에서 도움을 줄 수 있습니다 :
https://en.wikipedia.org/wiki/List_of_country_calling_codes

각 숫자가 분기 인 트리 구조의 데이터를 구문 분석합니다.

마지막 지점에 도달 할 때까지 숫자로 트리 숫자를 이동하십시오. 이것이 국가 코드입니다.