libphonenumber

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2021 License: MIT Imports: 11 Imported by: 154

README

libphonenumber

golang port of Google's libphonenumber

forthebadge

Build Status GoDoc

Status

This library is fully stable and is used in production by several companies.

Examples

Super simple to use.

To get a phone number
num, err := libphonenumber.Parse("6502530000", "US")
To format a number
// num is a *libphonenumber.PhoneNumber
formattedNum := libphonenumber.Format(num, libphonenumber.NATIONAL)
To get the area code of a number
// Parse the number.
num, err := libphonenumber.Parse("1234567890", "US")
if err != nil {
        // Handle error appropriately.
}

// Get the cleaned number and the length of the area code.
natSigNumber := libphonenumber.GetNationalSignificantNumber(num)
geoCodeLength := libphonenumber.GetLengthOfGeographicalAreaCode(num)

// Extract the area code.
areaCode := ""
if geoCodeLength > 0 {
        areaCode = natSigNumber[0:geoCodeLength]
}
fmt.Println(areaCode)

Documentation

Overview

Package i18n_phonenumbers is a generated protocol buffer package.

It is generated from these files:

google_libphonenumber/resources/phonemetadata.proto
google_libphonenumber/resources/phonenumber.proto

It has these top-level messages:

NumberFormat
PhoneNumberDesc
PhoneMetadata
PhoneMetadataCollection
PhoneNumber

Index

Constants

View Source
const (
	// MIN_LENGTH_FOR_NSN is the minimum and maximum length of the national significant number.
	MIN_LENGTH_FOR_NSN = 2
	// MAX_LENGTH_FOR_NSN: The ITU says the maximum length should be 15, but we have
	// found longer numbers in Germany.
	MAX_LENGTH_FOR_NSN = 17
	// MAX_LENGTH_COUNTRY_CODE is the maximum length of the country calling code.
	MAX_LENGTH_COUNTRY_CODE = 3
	// MAX_INPUT_STRING_LENGTH caps input strings for parsing at 250 chars.
	// This prevents malicious input from overflowing the regular-expression
	// engine.
	MAX_INPUT_STRING_LENGTH = 250

	// UNKNOWN_REGION is the region-code for the unknown region.
	UNKNOWN_REGION = "ZZ"

	NANPA_COUNTRY_CODE = 1

	// The prefix that needs to be inserted in front of a Colombian
	// landline number when dialed from a mobile phone in Colombia.
	COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3"

	// The PLUS_SIGN signifies the international prefix.
	PLUS_SIGN = '+'

	STAR_SIGN = '*'

	RFC3966_EXTN_PREFIX     = ";ext="
	RFC3966_PREFIX          = "tel:"
	RFC3966_PHONE_CONTEXT   = ";phone-context="
	RFC3966_ISDN_SUBADDRESS = ";isub="

	// Regular expression of acceptable punctuation found in phone
	// numbers. This excludes punctuation found as a leading character
	// only. This consists of dash characters, white space characters,
	// full stops, slashes, square brackets, parentheses and tildes. It
	// also includes the letter 'x' as that is found as a placeholder
	// for carrier information in some phone numbers. Full-width variants
	// are also present.
	VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
		"\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D." +
		"\\[\\]/~\u2053\u223C\uFF5E"

	DIGITS = "\\p{Nd}"

	// We accept alpha characters in phone numbers, ASCII only, upper
	// and lower case.
	VALID_ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	PLUS_CHARS  = "+\uFF0B"

	// This is defined by ICU as the unknown time zone.
	UNKNOWN_TIMEZONE = "Etc/Unknown"
)
View Source
const Default_NumberFormat_NationalPrefixOptionalWhenFormatting bool = false
View Source
const Default_PhoneMetadata_LeadingZeroPossible bool = false
View Source
const Default_PhoneMetadata_MainCountryForCode bool = false
View Source
const Default_PhoneMetadata_MobileNumberPortableRegion bool = false
View Source
const Default_PhoneMetadata_SameMobileAndFixedLinePattern bool = false
View Source
const Default_PhoneNumber_NumberOfLeadingZeros int32 = 1
View Source
const MAX_REGION_CODE_LENGTH = 7

Variables

View Source
var (
	// Map of country calling codes that use a mobile token before the
	// area code. One example of when this is relevant is when determining
	// the length of the national destination code, which should be the
	// length of the area code plus the length of the mobile token.
	MOBILE_TOKEN_MAPPINGS = map[int]string{
		52: "1",
		54: "9",
	}

	// A map that contains characters that are essential when dialling.
	// That means any of the characters in this map must not be removed
	// from a number when dialling, otherwise the call will not reach
	// the intended destination.
	DIALLABLE_CHAR_MAPPINGS = map[rune]rune{
		'1':       '1',
		'2':       '2',
		'3':       '3',
		'4':       '4',
		'5':       '5',
		'6':       '6',
		'7':       '7',
		'8':       '8',
		'9':       '9',
		'0':       '0',
		PLUS_SIGN: PLUS_SIGN,
		'*':       '*',
	}

	// Only upper-case variants of alpha characters are stored.
	ALPHA_MAPPINGS = map[rune]rune{
		'A': '2',
		'B': '2',
		'C': '2',
		'D': '3',
		'E': '3',
		'F': '3',
		'G': '4',
		'H': '4',
		'I': '4',
		'J': '5',
		'K': '5',
		'L': '5',
		'M': '6',
		'N': '6',
		'O': '6',
		'P': '7',
		'Q': '7',
		'R': '7',
		'S': '7',
		'T': '8',
		'U': '8',
		'V': '8',
		'W': '9',
		'X': '9',
		'Y': '9',
		'Z': '9',
	}

	// For performance reasons, amalgamate both into one map.
	ALPHA_PHONE_MAPPINGS = map[rune]rune{
		'1':       '1',
		'2':       '2',
		'3':       '3',
		'4':       '4',
		'5':       '5',
		'6':       '6',
		'7':       '7',
		'8':       '8',
		'9':       '9',
		'0':       '0',
		PLUS_SIGN: PLUS_SIGN,
		'*':       '*',
		'A':       '2',
		'B':       '2',
		'C':       '2',
		'D':       '3',
		'E':       '3',
		'F':       '3',
		'G':       '4',
		'H':       '4',
		'I':       '4',
		'J':       '5',
		'K':       '5',
		'L':       '5',
		'M':       '6',
		'N':       '6',
		'O':       '6',
		'P':       '7',
		'Q':       '7',
		'R':       '7',
		'S':       '7',
		'T':       '8',
		'U':       '8',
		'V':       '8',
		'W':       '9',
		'X':       '9',
		'Y':       '9',
		'Z':       '9',
	}

	// Separate map of all symbols that we wish to retain when formatting
	// alpha numbers. This includes digits, ASCII letters and number
	// grouping symbols such as "-" and " ".
	ALL_PLUS_NUMBER_GROUPING_SYMBOLS = map[rune]rune{
		'1':       '1',
		'2':       '2',
		'3':       '3',
		'4':       '4',
		'5':       '5',
		'6':       '6',
		'7':       '7',
		'8':       '8',
		'9':       '9',
		'0':       '0',
		PLUS_SIGN: PLUS_SIGN,
		'*':       '*',
		'A':       'A',
		'B':       'B',
		'C':       'C',
		'D':       'D',
		'E':       'E',
		'F':       'F',
		'G':       'G',
		'H':       'H',
		'I':       'I',
		'J':       'J',
		'K':       'K',
		'L':       'L',
		'M':       'M',
		'N':       'N',
		'O':       'O',
		'P':       'P',
		'Q':       'Q',
		'R':       'R',
		'S':       'S',
		'T':       'T',
		'U':       'U',
		'V':       'V',
		'W':       'W',
		'X':       'X',
		'Y':       'Y',
		'Z':       'Z',
		'a':       'A',
		'b':       'B',
		'c':       'C',
		'd':       'D',
		'e':       'E',
		'f':       'F',
		'g':       'G',
		'h':       'H',
		'i':       'I',
		'j':       'J',
		'k':       'K',
		'l':       'L',
		'm':       'M',
		'n':       'N',
		'o':       'O',
		'p':       'P',
		'q':       'Q',
		'r':       'R',
		's':       'S',
		't':       'T',
		'u':       'U',
		'v':       'V',
		'w':       'W',
		'x':       'X',
		'y':       'Y',
		'z':       'Z',
		'-':       '-',
		'\uFF0D':  '-',
		'\u2010':  '-',
		'\u2011':  '-',
		'\u2012':  '-',
		'\u2013':  '-',
		'\u2014':  '-',
		'\u2015':  '-',
		'\u2212':  '-',
		'/':       '/',
		'\uFF0F':  '/',
		' ':       ' ',
		'\u3000':  ' ',
		'\u2060':  ' ',
		'.':       '.',
		'\uFF0E':  '.',
	}

	// Pattern that makes it easy to distinguish whether a region has a
	// unique international dialing prefix or not. If a region has a
	// unique international prefix (e.g. 011 in USA), it will be
	// represented as a string that contains a sequence of ASCII digits.
	// If there are multiple available international prefixes in a
	// region, they will be represented as a regex string that always
	// contains character(s) other than ASCII digits.
	// Note this regex also includes tilde, which signals waiting for the tone.
	UNIQUE_INTERNATIONAL_PREFIX = regexp.MustCompile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?")

	PLUS_CHARS_PATTERN      = regexp.MustCompile("[" + PLUS_CHARS + "]+")
	SEPARATOR_PATTERN       = regexp.MustCompile("[" + VALID_PUNCTUATION + "]+")
	NOT_SEPARATOR_PATTERN   = regexp.MustCompile("[^" + VALID_PUNCTUATION + "]+")
	CAPTURING_DIGIT_PATTERN = regexp.MustCompile("(" + DIGITS + ")")

	// Regular expression of acceptable characters that may start a
	// phone number for the purposes of parsing. This allows us to
	// strip away meaningless prefixes to phone numbers that may be
	// mistakenly given to us. This consists of digits, the plus symbol
	// and arabic-indic digits. This does not contain alpha characters,
	// although they may be used later in the number. It also does not
	// include other punctuation, as this will be stripped later during
	// parsing and is of no information value when parsing a number.
	VALID_START_CHAR         = "[" + PLUS_CHARS + DIGITS + "]"
	VALID_START_CHAR_PATTERN = regexp.MustCompile(VALID_START_CHAR)

	// Regular expression of characters typically used to start a second
	// phone number for the purposes of parsing. This allows us to strip
	// off parts of the number that are actually the start of another
	// number, such as for: (530) 583-6985 x302/x2303 -> the second
	// extension here makes this actually two phone numbers,
	// (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
	// extension so that the first number is parsed correctly.
	SECOND_NUMBER_START         = "[\\\\/] *x"
	SECOND_NUMBER_START_PATTERN = regexp.MustCompile(SECOND_NUMBER_START)

	// Regular expression of trailing characters that we want to remove.
	// We remove all characters that are not alpha or numerical characters.
	// The hash character is retained here, as it may signify the previous
	// block was an extension.
	UNWANTED_END_CHARS        = "[[\\P{N}&&\\P{L}]&&[^#]]+$"
	UNWANTED_END_CHAR_PATTERN = regexp.MustCompile(UNWANTED_END_CHARS)

	// We use this pattern to check if the phone number has at least three
	// letters in it - if so, then we treat it as a number where some
	// phone-number digits are represented by letters.
	VALID_ALPHA_PHONE_PATTERN = regexp.MustCompile("(?:.*?[A-Za-z]){3}.*")

	// Regular expression of viable phone numbers. This is location
	// independent. Checks we have at least three leading digits, and
	// only valid punctuation, alpha characters and digits in the phone
	// number. Does not include extension data. The symbol 'x' is allowed
	// here as valid punctuation since it is often used as a placeholder
	// for carrier codes, for example in Brazilian phone numbers. We also
	// allow multiple "+" characters at the start.
	// Corresponds to the following:
	// [digits]{minLengthNsn}|
	// plus_sign*(
	//    ([punctuation]|[star])*[digits]
	// ){3,}([punctuation]|[star]|[digits]|[alpha])*
	//
	// The first reg-ex is to allow short numbers (two digits long) to be
	// parsed if they are entered as "15" etc, but only if there is no
	// punctuation in them. The second expression restricts the number of
	// digits to three or more, but then allows them to be in
	// international form, and to have alpha-characters and punctuation.
	//
	// Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
	VALID_PHONE_NUMBER = DIGITS + "{" + strconv.Itoa(MIN_LENGTH_FOR_NSN) + "}" + "|" +
		"[" + PLUS_CHARS + "]*(?:[" + VALID_PUNCTUATION + string(STAR_SIGN) +
		"]*" + DIGITS + "){3,}[" +
		VALID_PUNCTUATION + string(STAR_SIGN) + VALID_ALPHA + DIGITS + "]*"

	// Default extension prefix to use when formatting. This will be put
	// in front of any extension component of the number, after the main
	// national number is formatted. For example, if you wish the default
	// extension formatting to be " extn: 3456", then you should specify
	// " extn: " here as the default extension prefix. This can be
	// overridden by region-specific preferences.
	DEFAULT_EXTN_PREFIX = " ext. "

	// Pattern to capture digits used in an extension. Places a maximum
	// length of "7" for an extension.
	CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})"

	// Regexp of all possible ways to write extensions, for use when
	// parsing. This will be run as a case-insensitive regexp match.
	// Wide character versions are also provided after each ASCII version.
	// There are three regular expressions here. The first covers RFC 3966
	// format, where the extension is added using ";ext=". The second more
	// generic one starts with optional white space and ends with an
	// optional full stop (.), followed by zero or more spaces/tabs and then
	// the numbers themselves. The other one covers the special case of
	// American numbers where the extension is written with a hash at the
	// end, such as "- 503#". Note that the only capturing groups should
	// be around the digits that you want to capture as part of the
	// extension, or else parsing will fail! Canonical-equivalence doesn't
	// seem to be an option with Android java, so we allow two options
	// for representing the accented o - the character itself, and one in
	// the unicode decomposed form with the combining acute accent.
	EXTN_PATTERNS_FOR_PARSING = RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
		"(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
		"[,x\uFF58#\uFF03~\uFF5E]|int|anexo|\uFF49\uFF4E\uFF54)" +
		"[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
		"[- ]+(" + DIGITS + "{1,5})#"
	EXTN_PATTERNS_FOR_MATCHING = RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
		"(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
		"[x\uFF58#\uFF03~\uFF5E]|int|anexo|\uFF49\uFF4E\uFF54)" +
		"[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
		"[- ]+(" + DIGITS + "{1,5})#"

	// Regexp of all known extension prefixes used by different regions
	// followed by 1 or more valid digits, for use when parsing.
	EXTN_PATTERN = regexp.MustCompile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$")

	// We append optionally the extension pattern to the end here, as a
	// valid phone number may have an extension prefix appended,
	// followed by 1 or more digits.
	VALID_PHONE_NUMBER_PATTERN = regexp.MustCompile(
		VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?")

	NON_DIGITS_PATTERN = regexp.MustCompile("(\\D+)")
	DIGITS_PATTERN     = regexp.MustCompile("(\\d+)")

	// The FIRST_GROUP_PATTERN was originally set to $1 but there are some
	// countries for which the first group is not used in the national
	// pattern (e.g. Argentina) so the $1 group does not match correctly.
	// Therefore, we use \d, so that the first group actually used in the
	// pattern will be matched.
	FIRST_GROUP_PATTERN = regexp.MustCompile("(\\$\\d)")
	NP_PATTERN          = regexp.MustCompile("\\$NP")
	FG_PATTERN          = regexp.MustCompile("\\$FG")
	CC_PATTERN          = regexp.MustCompile("\\$CC")

	// A pattern that is used to determine if the national prefix
	// formatting rule has the first group only, i.e., does not start
	// with the national prefix. Note that the pattern explicitly allows
	// for unbalanced parentheses.
	FIRST_GROUP_ONLY_PREFIX_PATTERN = regexp.MustCompile("\\(?\\$1\\)?")

	REGION_CODE_FOR_NON_GEO_ENTITY = "001"
)
View Source
var (
	ErrInvalidCountryCode = errors.New("invalid country code")
	ErrNotANumber         = errors.New("The phone number supplied was empty.")
	ErrTooShortNSN        = errors.New("The string supplied is too short to be a phone number.")
)
View Source
var CountryCodeToRegion = map[int][]string{}/* 216 elements not displayed */
View Source
var CountryCodeToTimeZones = map[int][]string{}/* 2054 elements not displayed */
View Source
var ErrEmptyMetadata = errors.New("empty metadata")
View Source
var ErrNumTooLong = errors.New("The string supplied is too long to be a phone number.")
View Source
var ErrTooShortAfterIDD = errors.New("Phone number had an IDD, but " +
	"after this was not long enough to be a viable phone number.")
View Source
var PhoneNumber_CountryCodeSource_name = map[int32]string{
	0:  "UNSPECIFIED",
	1:  "FROM_NUMBER_WITH_PLUS_SIGN",
	5:  "FROM_NUMBER_WITH_IDD",
	10: "FROM_NUMBER_WITHOUT_PLUS_SIGN",
	20: "FROM_DEFAULT_COUNTRY",
}
View Source
var PhoneNumber_CountryCodeSource_value = map[string]int32{
	"UNSPECIFIED":                   0,
	"FROM_NUMBER_WITH_PLUS_SIGN":    1,
	"FROM_NUMBER_WITH_IDD":          5,
	"FROM_NUMBER_WITHOUT_PLUS_SIGN": 10,
	"FROM_DEFAULT_COUNTRY":          20,
}

Functions

func AllNumberGroupsAreExactlyPresent

func AllNumberGroupsAreExactlyPresent(
	number *PhoneNumber,
	normalizedCandidate string,
	formattedNumberGroups []string) bool

func AllNumberGroupsRemainGrouped

func AllNumberGroupsRemainGrouped(
	number *PhoneNumber,
	normalizedCandidate string,
	formattedNumberGroups []string) bool

func CheckNumberGroupingIsValid

func CheckNumberGroupingIsValid(
	number *PhoneNumber,
	candidate string,
	fn func(*PhoneNumber, string, []string) bool) bool

func ContainsMoreThanOneSlashInNationalNumber

func ContainsMoreThanOneSlashInNationalNumber(
	number *PhoneNumber,
	candidate string) bool

func ContainsOnlyValidXChars

func ContainsOnlyValidXChars(number *PhoneNumber, candidate string) bool

func ConvertAlphaCharactersInNumber

func ConvertAlphaCharactersInNumber(number string) string

Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.

func Format

func Format(number *PhoneNumber, numberFormat PhoneNumberFormat) string

Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied.

func FormatByPattern

func FormatByPattern(number *PhoneNumber,
	numberFormat PhoneNumberFormat,
	userDefinedFormats []*NumberFormat) string

Formats a phone number in the specified format using client-defined formatting rules. Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied.

func FormatInOriginalFormat

func FormatInOriginalFormat(number *PhoneNumber, regionCallingFrom string) string

Formats a phone number using the original phone number format that the number is parsed from. The original format is embedded in the country_code_source field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into the NATIONAL format by default. When the number contains a leading zero and this is unexpected for this country, or we don't have a formatting pattern for the number, the method returns the raw input when it is available.

Note this method guarantees no digit will be inserted, removed or modified as a result of formatting.

func FormatNationalNumberWithCarrierCode

func FormatNationalNumberWithCarrierCode(number *PhoneNumber, carrierCode string) string

Formats a phone number in national format for dialing using the carrier as specified in the carrierCode. The carrierCode will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrierCode contains an empty string, returns the number in national format without any carrier code.

func FormatNationalNumberWithPreferredCarrierCode

func FormatNationalNumberWithPreferredCarrierCode(
	number *PhoneNumber,
	fallbackCarrierCode string) string

Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing, use the fallbackCarrierCode passed in instead. If there is no preferredDomesticCarrierCode, and the fallbackCarrierCode contains an empty string, return the number in national format without any carrier code.

Use formatNationalNumberWithCarrierCode instead if the carrier code passed in should take precedence over the number's preferredDomesticCarrierCode when formatting.

func FormatNumberForMobileDialing

func FormatNumberForMobileDialing(
	number *PhoneNumber,
	regionCallingFrom string,
	withFormatting bool) string

Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region. If the number cannot be reached from the region (e.g. some countries block toll-free numbers from being called outside of the country), the method returns an empty string.

func FormatOutOfCountryCallingNumber

func FormatOutOfCountryCallingNumber(
	number *PhoneNumber,
	regionCallingFrom string) string

Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is supplied, we format the number in its INTERNATIONAL format. If the country calling code is the same as that of the region where the number is from, then NATIONAL formatting will be applied.

If the number itself has a country calling code of zero or an otherwise invalid country calling code, then we return the number with no formatting applied.

Note this function takes care of the case for calling inside of NANPA and between Russia and Kazakhstan (who share the same country calling code). In those cases, no international prefix is used. For regions which have multiple international prefixes, the number in its INTERNATIONAL format will be returned instead.

func FormatOutOfCountryKeepingAlphaChars

func FormatOutOfCountryKeepingAlphaChars(
	number *PhoneNumber,
	regionCallingFrom string) string

Formats a phone number for out-of-country dialing purposes.

Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping information, as specified by characters such as "-" and " ", will be retained.

Caveats:

  • This will not produce good results if the country calling code is both present in the raw input _and_ is the start of the national number. This is not a problem in the regions which typically use alpha numbers.
  • This will also not produce good results if the raw input has any grouping information within the first three digits of the national number, and if the function needs to strip preceding digits/words in the raw input before these digits. Normally people group the first three digits together so this is not a huge problem - and will be fixed if it proves to be so.

func FormatWithBuf

func FormatWithBuf(
	number *PhoneNumber,
	numberFormat PhoneNumberFormat,
	formattedNumber *builder.Builder)

Same as Format(PhoneNumber, PhoneNumberFormat), but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times.

func GetCountryCodeForRegion

func GetCountryCodeForRegion(regionCode string) int

Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand.

func GetCountryMobileToken

func GetCountryMobileToken(countryCallingCode int) string

Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string. A mobile token is a number inserted before the area code when dialing a mobile number from that country from abroad.

func GetLengthOfGeographicalAreaCode

func GetLengthOfGeographicalAreaCode(number *PhoneNumber) int

Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used:

number, err := Parse("16502530000", "US");
// ... deal with err appropriately ...
nationalSignificantNumber := GetNationalSignificantNumber(number);
var areaCode, subscriberNumber;

int areaCodeLength = GetLengthOfGeographicalAreaCode(number);
if (areaCodeLength > 0) {
  areaCode = nationalSignificantNumber[0:areaCodeLength];
  subscriberNumber = nationalSignificantNumber[areaCodeLength:];
} else {
  areaCode = "";
  subscriberNumber = nationalSignificantNumber;
}

N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general national_number instead. Read the following carefully before deciding to use this method:

  • geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces.
  • subscriber numbers may not be diallable from all devices (notably mobile devices, which typically requires the full national_number to be dialled in most regions).
  • most non-geographical numbers have no area codes, including numbers from non-geographical entities
  • some geographical numbers have no area codes.

func GetLengthOfNationalDestinationCode

func GetLengthOfNationalDestinationCode(number *PhoneNumber) int

Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number. The NDC of a phone number is normally the first group of digit(s) right after the country calling code when the number is formatted in the international format, if there is a subscriber number part that follows. An example of how this could be used:

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber number = phoneUtil.parse("18002530000", "US");
String nationalSignificantNumber = phoneUtil.GetNationalSignificantNumber(number);
String nationalDestinationCode;
String subscriberNumber;

int nationalDestinationCodeLength =
    phoneUtil.GetLengthOfNationalDestinationCode(number);
if nationalDestinationCodeLength > 0 {
    nationalDestinationCode = nationalSignificantNumber.substring(0,
        nationalDestinationCodeLength);
    subscriberNumber = nationalSignificantNumber.substring(
        nationalDestinationCodeLength);
} else {
    nationalDestinationCode = "";
    subscriberNumber = nationalSignificantNumber;
}

Refer to the unittests to see the difference between this function and GetLengthOfGeographicalAreaCode().

func GetNationalSignificantNumber

func GetNationalSignificantNumber(number *PhoneNumber) string

Gets the national significant number of the a phone number. Note a national significant number doesn't contain a national prefix or any formatting.

func GetNddPrefixForRegion

func GetNddPrefixForRegion(regionCode string, stripNonDigits bool) string

Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return null.

Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required.

func GetRegionCodeForCountryCode

func GetRegionCodeForCountryCode(countryCallingCode int) string

Returns the region code that matches the specific country calling code. In the case of no region code being found, ZZ will be returned. In the case of multiple regions, the one designated in the metadata as the "main" region for this calling code will be returned. If the countryCallingCode entered is valid but doesn't match a specific region (such as in the case of non-geographical calling codes like 800) the value "001" will be returned (corresponding to the value for World in the UN M.49 schema).

func GetRegionCodeForNumber

func GetRegionCodeForNumber(number *PhoneNumber) string

Returns the region where a phone number is from. This could be used for geocoding at the region level.

func GetRegionCodesForCountryCode

func GetRegionCodesForCountryCode(countryCallingCode int) []string

Returns a list with the region codes that match the specific country calling code. For non-geographical country calling codes, the region code 001 is returned. Also, in the case of no region code being found, an empty list is returned.

func GetSupportedGlobalNetworkCallingCodes

func GetSupportedGlobalNetworkCallingCodes() map[int]struct{}

Convenience method to get a list of what global network calling codes the library has metadata for.

func GetSupportedRegions

func GetSupportedRegions() map[string]struct{}

Convenience method to get a list of what regions the library has metadata for.

func GetTimeZonesForRegion

func GetTimeZonesForRegion(number string) ([]string, error)

Returns a slice of Timezones corresponding to the number passed or error when it is impossible to convert the string to int The algorythm tries to match the timezones starting from the maximum number of phone number digits and decreasing until it finds one or reaches 0

func IsAlphaNumber

func IsAlphaNumber(number string) bool

Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity number will start with at least 3 digits and will have three or more alpha characters. This does not do region-specific checks - to work out if this number is actually valid for a region, it should be parsed and methods such as IsPossibleNumberWithReason() and IsValidNumber() should be used.

func IsMobileNumberPortableRegion

func IsMobileNumberPortableRegion(regionCode string) bool

Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability.

func IsNANPACountry

func IsNANPACountry(regionCode string) bool

Checks if this is a region under the North American Numbering Plan Administration (NANPA).

func IsNationalPrefixPresentIfRequired

func IsNationalPrefixPresentIfRequired(number *PhoneNumber) bool

func IsPossibleNumber

func IsPossibleNumber(number *PhoneNumber) bool

Convenience wrapper around IsPossibleNumberWithReason(). Instead of returning the reason for failure, this method returns a boolean value.

func IsValidNumber

func IsValidNumber(number *PhoneNumber) bool

Tests whether a phone number matches a valid pattern. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself.

func IsValidNumberForRegion

func IsValidNumberForRegion(number *PhoneNumber, regionCode string) bool

Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use IsValidNumber() instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable.

func NormalizeDigitsOnly

func NormalizeDigitsOnly(number string) string

Normalizes a string of characters representing a phone number. This converts wide-ascii and arabic-indic numerals to European numerals, and strips punctuation and alpha characters.

func ParseAndKeepRawInputToNumber

func ParseAndKeepRawInputToNumber(
	numberToParse, defaultRegion string,
	phoneNumber *PhoneNumber) error

Same as ParseAndKeepRawInput(String, String), but accepts a mutable PhoneNumber as a parameter to decrease object creation when invoked many times.

func ParseToNumber

func ParseToNumber(numberToParse, defaultRegion string, phoneNumber *PhoneNumber) error

Same as Parse(string, string), but accepts mutable PhoneNumber as a parameter to decrease object creation when invoked many times.

func TruncateTooLongNumber

func TruncateTooLongNumber(number *PhoneNumber) bool

Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified.

Types

type Leniency

type Leniency int

TODO(ttacon): leniency comments?

const (
	POSSIBLE Leniency = iota
	VALID
	STRICT_GROUPING
	EXACT_GROUPING
)

func (Leniency) Verify

func (l Leniency) Verify(number *PhoneNumber, candidate string) bool

type MatchType

type MatchType int
const (
	NOT_A_NUMBER MatchType = iota
	NO_MATCH
	SHORT_NSN_MATCH
	NSN_MATCH
	EXACT_MATCH
)

func IsNumberMatch

func IsNumberMatch(firstNumber, secondNumber string) MatchType

Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for IsNumberMatch(PhoneNumber, PhoneNumber). No default region is known.

type NumberFormat

type NumberFormat struct {
	// pattern is a regex that is used to match the national (significant)
	// number. For example, the pattern "(20)(\d{4})(\d{4})" will match number
	// "2070313000", which is the national (significant) number for Google London.
	// Note the presence of the parentheses, which are capturing groups what
	// specifies the grouping of numbers.
	Pattern *string `protobuf:"bytes,1,req,name=pattern" json:"pattern,omitempty"`
	// format specifies how the national (significant) number matched by
	// pattern should be formatted.
	// Using the same example as above, format could contain "$1 $2 $3",
	// meaning that the number should be formatted as "20 7031 3000".
	// Each $x are replaced by the numbers captured by group x in the
	// regex specified by pattern.
	Format *string `protobuf:"bytes,2,req,name=format" json:"format,omitempty"`
	// This field is a regex that is used to match a certain number of digits
	// at the beginning of the national (significant) number. When the match is
	// successful, the accompanying pattern and format should be used to format
	// this number. For example, if leading_digits="[1-3]|44", then all the
	// national numbers starting with 1, 2, 3 or 44 should be formatted using the
	// accompanying pattern and format.
	//
	// The first leadingDigitsPattern matches up to the first three digits of the
	// national (significant) number; the next one matches the first four digits,
	// then the first five and so on, until the leadingDigitsPattern can uniquely
	// identify one pattern and format to be used to format the number.
	//
	// In the case when only one formatting pattern exists, no
	// leading_digits_pattern is needed.
	LeadingDigitsPattern []string `protobuf:"bytes,3,rep,name=leading_digits_pattern,json=leadingDigitsPattern" json:"leading_digits_pattern,omitempty"`
	// This field specifies how the national prefix ($NP) together with the first
	// group ($FG) in the national significant number should be formatted in
	// the NATIONAL format when a national prefix exists for a certain country.
	// For example, when this field contains "($NP$FG)", a number from Beijing,
	// China (whose $NP = 0), which would by default be formatted without
	// national prefix as 10 1234 5678 in NATIONAL format, will instead be
	// formatted as (010) 1234 5678; to format it as (0)10 1234 5678, the field
	// would contain "($NP)$FG". Note $FG should always be present in this field,
	// but $NP can be omitted. For example, having "$FG" could indicate the
	// number should be formatted in NATIONAL format without the national prefix.
	// This is commonly used to override the rule specified for the territory in
	// the XML file.
	//
	// When this field is missing, a number will be formatted without national
	// prefix in NATIONAL format. This field does not affect how a number
	// is formatted in other formats, such as INTERNATIONAL.
	NationalPrefixFormattingRule *string `` /* 142-byte string literal not displayed */
	// This field specifies whether the $NP can be omitted when formatting a
	// number in national format, even though it usually wouldn't be. For example,
	// a UK number would be formatted by our library as 020 XXXX XXXX. If we have
	// commonly seen this number written by people without the leading 0, for
	// example as (20) XXXX XXXX, this field would be set to true. This will be
	// inherited from the value set for the territory in the XML file, unless a
	// national_prefix_optional_when_formatting is defined specifically for this
	// NumberFormat.
	NationalPrefixOptionalWhenFormatting *bool `` /* 175-byte string literal not displayed */
	// This field specifies how any carrier code ($CC) together with the first
	// group ($FG) in the national significant number should be formatted
	// when formatWithCarrierCode is called, if carrier codes are used for a
	// certain country.
	DomesticCarrierCodeFormattingRule *string `` /* 159-byte string literal not displayed */
	XXX_unrecognized                  []byte  `json:"-"`
}

func (*NumberFormat) Descriptor

func (*NumberFormat) Descriptor() ([]byte, []int)

func (*NumberFormat) GetDomesticCarrierCodeFormattingRule

func (m *NumberFormat) GetDomesticCarrierCodeFormattingRule() string

func (*NumberFormat) GetFormat

func (m *NumberFormat) GetFormat() string

func (*NumberFormat) GetLeadingDigitsPattern

func (m *NumberFormat) GetLeadingDigitsPattern() []string

func (*NumberFormat) GetNationalPrefixFormattingRule

func (m *NumberFormat) GetNationalPrefixFormattingRule() string

func (*NumberFormat) GetNationalPrefixOptionalWhenFormatting

func (m *NumberFormat) GetNationalPrefixOptionalWhenFormatting() bool

func (*NumberFormat) GetPattern

func (m *NumberFormat) GetPattern() string

func (*NumberFormat) ProtoMessage

func (*NumberFormat) ProtoMessage()

func (*NumberFormat) Reset

func (m *NumberFormat) Reset()

func (*NumberFormat) String

func (m *NumberFormat) String() string

type PhoneMetadata

type PhoneMetadata struct {
	// The general_desc contains information which is a superset of descriptions
	// for all types of phone numbers. If any element is missing in the
	// description of a specific type in the XML file, the element will inherit
	// from its counterpart in the general_desc. For all types that are generally
	// relevant to normal phone numbers, if the whole type is missing in the
	// PhoneNumberMetadata XML file, it will not have national number data, and
	// the possible lengths will be [-1].
	GeneralDesc     *PhoneNumberDesc `protobuf:"bytes,1,opt,name=general_desc,json=generalDesc" json:"general_desc,omitempty"`
	FixedLine       *PhoneNumberDesc `protobuf:"bytes,2,opt,name=fixed_line,json=fixedLine" json:"fixed_line,omitempty"`
	Mobile          *PhoneNumberDesc `protobuf:"bytes,3,opt,name=mobile" json:"mobile,omitempty"`
	TollFree        *PhoneNumberDesc `protobuf:"bytes,4,opt,name=toll_free,json=tollFree" json:"toll_free,omitempty"`
	PremiumRate     *PhoneNumberDesc `protobuf:"bytes,5,opt,name=premium_rate,json=premiumRate" json:"premium_rate,omitempty"`
	SharedCost      *PhoneNumberDesc `protobuf:"bytes,6,opt,name=shared_cost,json=sharedCost" json:"shared_cost,omitempty"`
	PersonalNumber  *PhoneNumberDesc `protobuf:"bytes,7,opt,name=personal_number,json=personalNumber" json:"personal_number,omitempty"`
	Voip            *PhoneNumberDesc `protobuf:"bytes,8,opt,name=voip" json:"voip,omitempty"`
	Pager           *PhoneNumberDesc `protobuf:"bytes,21,opt,name=pager" json:"pager,omitempty"`
	Uan             *PhoneNumberDesc `protobuf:"bytes,25,opt,name=uan" json:"uan,omitempty"`
	Emergency       *PhoneNumberDesc `protobuf:"bytes,27,opt,name=emergency" json:"emergency,omitempty"`
	Voicemail       *PhoneNumberDesc `protobuf:"bytes,28,opt,name=voicemail" json:"voicemail,omitempty"`
	ShortCode       *PhoneNumberDesc `protobuf:"bytes,29,opt,name=short_code,json=shortCode" json:"short_code,omitempty"`
	StandardRate    *PhoneNumberDesc `protobuf:"bytes,30,opt,name=standard_rate,json=standardRate" json:"standard_rate,omitempty"`
	CarrierSpecific *PhoneNumberDesc `protobuf:"bytes,31,opt,name=carrier_specific,json=carrierSpecific" json:"carrier_specific,omitempty"`
	SmsServices     *PhoneNumberDesc `protobuf:"bytes,33,opt,name=sms_services,json=smsServices" json:"sms_services,omitempty"`
	// The rules here distinguish the numbers that are only able to be dialled
	// nationally.
	NoInternationalDialling *PhoneNumberDesc `` /* 126-byte string literal not displayed */
	// The CLDR 2-letter representation of a country/region, with the exception of
	// "country calling codes" used for non-geographical entities, such as
	// Universal International Toll Free Number (+800). These are all given the ID
	// "001", since this is the numeric region code for the world according to UN
	// M.49: http://en.wikipedia.org/wiki/UN_M.49
	Id *string `protobuf:"bytes,9,req,name=id" json:"id,omitempty"`
	// The country calling code that one would dial from overseas when trying to
	// dial a phone number in this country. For example, this would be "64" for
	// New Zealand.
	CountryCode *int32 `protobuf:"varint,10,opt,name=country_code,json=countryCode" json:"country_code,omitempty"`
	// The international_prefix of country A is the number that needs to be
	// dialled from country A to another country (country B). This is followed
	// by the country code for country B. Note that some countries may have more
	// than one international prefix, and for those cases, a regular expression
	// matching the international prefixes will be stored in this field.
	InternationalPrefix *string `protobuf:"bytes,11,opt,name=international_prefix,json=internationalPrefix" json:"international_prefix,omitempty"`
	// If more than one international prefix is present, a preferred prefix can
	// be specified here for out-of-country formatting purposes. If this field is
	// not present, and multiple international prefixes are present, then "+"
	// will be used instead.
	PreferredInternationalPrefix *string `` /* 141-byte string literal not displayed */
	// The national prefix of country A is the number that needs to be dialled
	// before the national significant number when dialling internally. This
	// would not be dialled when dialling internationally. For example, in New
	// Zealand, the number that would be locally dialled as 09 345 3456 would be
	// dialled from overseas as +64 9 345 3456. In this case, 0 is the national
	// prefix.
	NationalPrefix *string `protobuf:"bytes,12,opt,name=national_prefix,json=nationalPrefix" json:"national_prefix,omitempty"`
	// The preferred prefix when specifying an extension in this country. This is
	// used for formatting only, and if this is not specified, a suitable default
	// should be used instead. For example, if you wanted extensions to be
	// formatted in the following way:
	// 1 (365) 345 445 ext. 2345
	// " ext. "  should be the preferred extension prefix.
	PreferredExtnPrefix *string `protobuf:"bytes,13,opt,name=preferred_extn_prefix,json=preferredExtnPrefix" json:"preferred_extn_prefix,omitempty"`
	// This field is used for cases where the national prefix of a country
	// contains a carrier selection code, and is written in the form of a
	// regular expression. For example, to dial the number 2222-2222 in
	// Fortaleza, Brazil (area code 85) using the long distance carrier Oi
	// (selection code 31), one would dial 0 31 85 2222 2222. Assuming the
	// only other possible carrier selection code is 32, the field will
	// contain "03[12]".
	//
	// When it is missing from the XML file, this field inherits the value of
	// national_prefix, if that is present.
	NationalPrefixForParsing *string `` /* 131-byte string literal not displayed */
	// This field is only populated and used under very rare situations.
	// For example, mobile numbers in Argentina are written in two completely
	// different ways when dialed in-country and out-of-country
	// (e.g. 0343 15 555 1212 is exactly the same number as +54 9 343 555 1212).
	// This field is used together with national_prefix_for_parsing to transform
	// the number into a particular representation for storing in the phonenumber
	// proto buffer in those rare cases.
	NationalPrefixTransformRule *string `` /* 140-byte string literal not displayed */
	// Specifies whether the mobile and fixed-line patterns are the same or not.
	// This is used to speed up determining phone number type in countries where
	// these two types of phone numbers can never be distinguished.
	SameMobileAndFixedLinePattern *bool `` /* 157-byte string literal not displayed */
	// Note that the number format here is used for formatting only, not parsing.
	// Hence all the varied ways a user *may* write a number need not be recorded
	// - just the ideal way we would like to format it for them. When this element
	// is absent, the national significant number will be formatted as a whole
	// without any formatting applied.
	NumberFormat []*NumberFormat `protobuf:"bytes,19,rep,name=number_format,json=numberFormat" json:"number_format,omitempty"`
	// This field is populated only when the national significant number is
	// formatted differently when it forms part of the INTERNATIONAL format
	// and NATIONAL format. A case in point is mobile numbers in Argentina:
	// The number, which would be written in INTERNATIONAL format as
	// +54 9 343 555 1212, will be written as 0343 15 555 1212 for NATIONAL
	// format. In this case, the prefix 9 is inserted when dialling from
	// overseas, but otherwise the prefix 0 and the carrier selection code
	// 15 (inserted after the area code of 343) is used.
	// Note: this field is populated by setting a value for <intlFormat> inside
	// the <numberFormat> tag in the XML file. If <intlFormat> is not set then it
	// defaults to the same value as the <format> tag.
	//
	// Examples:
	//   To set the <intlFormat> to a different value than the <format>:
	//     <numberFormat pattern=....>
	//       <format>$1 $2 $3</format>
	//       <intlFormat>$1-$2-$3</intlFormat>
	//     </numberFormat>
	//
	//   To have a format only used for national formatting, set <intlFormat> to
	//   "NA":
	//     <numberFormat pattern=....>
	//       <format>$1 $2 $3</format>
	//       <intlFormat>NA</intlFormat>
	//     </numberFormat>
	IntlNumberFormat []*NumberFormat `protobuf:"bytes,20,rep,name=intl_number_format,json=intlNumberFormat" json:"intl_number_format,omitempty"`
	// This field is set when this country is considered to be the main country
	// for a calling code. It may not be set by more than one country with the
	// same calling code, and it should not be set by countries with a unique
	// calling code. This can be used to indicate that "GB" is the main country
	// for the calling code "44" for example, rather than Jersey or the Isle of
	// Man.
	MainCountryForCode *bool `protobuf:"varint,22,opt,name=main_country_for_code,json=mainCountryForCode,def=0" json:"main_country_for_code,omitempty"`
	// This field is populated only for countries or regions that share a country
	// calling code. If a number matches this pattern, it could belong to this
	// region. This is not intended as a replacement for IsValidForRegion since a
	// matching prefix is insufficient for a number to be valid. Furthermore, it
	// does not contain all the prefixes valid for a region - for example, 800
	// numbers are valid for all NANPA countries and are hence not listed here.
	// This field should be a regular expression of the expected prefix match.
	// It is used merely as a short-cut for working out which region a number
	// comes from in the case that there is only one, so leading_digit prefixes
	// should not overlap.
	LeadingDigits *string `protobuf:"bytes,23,opt,name=leading_digits,json=leadingDigits" json:"leading_digits,omitempty"`
	// Deprecated: do not use. Will be deletd when there are no references to this
	// later.
	LeadingZeroPossible *bool `protobuf:"varint,26,opt,name=leading_zero_possible,json=leadingZeroPossible,def=0" json:"leading_zero_possible,omitempty"`
	// This field is set when this country has implemented mobile number
	// portability. This means that transferring mobile numbers between carriers
	// is allowed. A consequence of this is that phone prefix to carrier mapping
	// is less reliable.
	MobileNumberPortableRegion *bool  `` /* 144-byte string literal not displayed */
	XXX_unrecognized           []byte `json:"-"`
}

If you add, remove, or rename fields, or change their semantics, check if you should change the excludable field sets or the behavior in MetadataFilter.

func (*PhoneMetadata) Descriptor

func (*PhoneMetadata) Descriptor() ([]byte, []int)

func (*PhoneMetadata) GetCarrierSpecific

func (m *PhoneMetadata) GetCarrierSpecific() *PhoneNumberDesc

func (*PhoneMetadata) GetCountryCode

func (m *PhoneMetadata) GetCountryCode() int32

func (*PhoneMetadata) GetEmergency

func (m *PhoneMetadata) GetEmergency() *PhoneNumberDesc

func (*PhoneMetadata) GetFixedLine

func (m *PhoneMetadata) GetFixedLine() *PhoneNumberDesc

func (*PhoneMetadata) GetGeneralDesc

func (m *PhoneMetadata) GetGeneralDesc() *PhoneNumberDesc

func (*PhoneMetadata) GetId

func (m *PhoneMetadata) GetId() string

func (*PhoneMetadata) GetInternationalPrefix

func (m *PhoneMetadata) GetInternationalPrefix() string

func (*PhoneMetadata) GetIntlNumberFormat

func (m *PhoneMetadata) GetIntlNumberFormat() []*NumberFormat

func (*PhoneMetadata) GetLeadingDigits

func (m *PhoneMetadata) GetLeadingDigits() string

func (*PhoneMetadata) GetLeadingZeroPossible

func (m *PhoneMetadata) GetLeadingZeroPossible() bool

func (*PhoneMetadata) GetMainCountryForCode

func (m *PhoneMetadata) GetMainCountryForCode() bool

func (*PhoneMetadata) GetMobile

func (m *PhoneMetadata) GetMobile() *PhoneNumberDesc

func (*PhoneMetadata) GetMobileNumberPortableRegion

func (m *PhoneMetadata) GetMobileNumberPortableRegion() bool

func (*PhoneMetadata) GetNationalPrefix

func (m *PhoneMetadata) GetNationalPrefix() string

func (*PhoneMetadata) GetNationalPrefixForParsing

func (m *PhoneMetadata) GetNationalPrefixForParsing() string

func (*PhoneMetadata) GetNationalPrefixTransformRule

func (m *PhoneMetadata) GetNationalPrefixTransformRule() string

func (*PhoneMetadata) GetNoInternationalDialling

func (m *PhoneMetadata) GetNoInternationalDialling() *PhoneNumberDesc

func (*PhoneMetadata) GetNumberFormat

func (m *PhoneMetadata) GetNumberFormat() []*NumberFormat

func (*PhoneMetadata) GetPager

func (m *PhoneMetadata) GetPager() *PhoneNumberDesc

func (*PhoneMetadata) GetPersonalNumber

func (m *PhoneMetadata) GetPersonalNumber() *PhoneNumberDesc

func (*PhoneMetadata) GetPreferredExtnPrefix

func (m *PhoneMetadata) GetPreferredExtnPrefix() string

func (*PhoneMetadata) GetPreferredInternationalPrefix

func (m *PhoneMetadata) GetPreferredInternationalPrefix() string

func (*PhoneMetadata) GetPremiumRate

func (m *PhoneMetadata) GetPremiumRate() *PhoneNumberDesc

func (*PhoneMetadata) GetSameMobileAndFixedLinePattern

func (m *PhoneMetadata) GetSameMobileAndFixedLinePattern() bool

func (*PhoneMetadata) GetSharedCost

func (m *PhoneMetadata) GetSharedCost() *PhoneNumberDesc

func (*PhoneMetadata) GetShortCode

func (m *PhoneMetadata) GetShortCode() *PhoneNumberDesc

func (*PhoneMetadata) GetSmsServices added in v1.0.1

func (m *PhoneMetadata) GetSmsServices() *PhoneNumberDesc

func (*PhoneMetadata) GetStandardRate

func (m *PhoneMetadata) GetStandardRate() *PhoneNumberDesc

func (*PhoneMetadata) GetTollFree

func (m *PhoneMetadata) GetTollFree() *PhoneNumberDesc

func (*PhoneMetadata) GetUan

func (m *PhoneMetadata) GetUan() *PhoneNumberDesc

func (*PhoneMetadata) GetVoicemail

func (m *PhoneMetadata) GetVoicemail() *PhoneNumberDesc

func (*PhoneMetadata) GetVoip

func (m *PhoneMetadata) GetVoip() *PhoneNumberDesc

func (*PhoneMetadata) ProtoMessage

func (*PhoneMetadata) ProtoMessage()

func (*PhoneMetadata) Reset

func (m *PhoneMetadata) Reset()

func (*PhoneMetadata) String

func (m *PhoneMetadata) String() string

type PhoneMetadataCollection

type PhoneMetadataCollection struct {
	Metadata         []*PhoneMetadata `protobuf:"bytes,1,rep,name=metadata" json:"metadata,omitempty"`
	XXX_unrecognized []byte           `json:"-"`
}

func (*PhoneMetadataCollection) Descriptor

func (*PhoneMetadataCollection) Descriptor() ([]byte, []int)

func (*PhoneMetadataCollection) GetMetadata

func (m *PhoneMetadataCollection) GetMetadata() []*PhoneMetadata

func (*PhoneMetadataCollection) ProtoMessage

func (*PhoneMetadataCollection) ProtoMessage()

func (*PhoneMetadataCollection) Reset

func (m *PhoneMetadataCollection) Reset()

func (*PhoneMetadataCollection) String

func (m *PhoneMetadataCollection) String() string

type PhoneNumber

type PhoneNumber struct {
	// The country calling code for this number, as defined by the International
	// Telecommunication Union (ITU). For example, this would be 1 for NANPA
	// countries, and 33 for France.
	CountryCode *int32 `protobuf:"varint,1,req,name=country_code,json=countryCode" json:"country_code,omitempty"`
	// The National (significant) Number, as defined in International
	// Telecommunication Union (ITU) Recommendation E.164, without any leading
	// zero. The leading-zero is stored separately if required, since this is an
	// uint64 and hence cannot store such information. Do not use this field
	// directly: if you want the national significant number, call the
	// getNationalSignificantNumber method of PhoneNumberUtil.
	//
	// For countries which have the concept of an "area code" or "national
	// destination code", this is included in the National (significant) Number.
	// Although the ITU says the maximum length should be 15, we have found longer
	// numbers in some countries e.g. Germany.
	// Note that the National (significant) Number does not contain the National
	// (trunk) prefix. Obviously, as a uint64, it will never contain any
	// formatting (hyphens, spaces, parentheses), nor any alphanumeric spellings.
	NationalNumber *uint64 `protobuf:"varint,2,req,name=national_number,json=nationalNumber" json:"national_number,omitempty"`
	// Extension is not standardized in ITU recommendations, except for being
	// defined as a series of numbers with a maximum length of 40 digits. It is
	// defined as a string here to accommodate for the possible use of a leading
	// zero in the extension (organizations have complete freedom to do so, as
	// there is no standard defined). Other than digits, some other dialling
	// characters such as "," (indicating a wait) may be stored here.
	Extension *string `protobuf:"bytes,3,opt,name=extension" json:"extension,omitempty"`
	// In some countries, the national (significant) number starts with one or
	// more "0"s without this being a national prefix or trunk code of some kind.
	// For example, the leading zero in the national (significant) number of an
	// Italian phone number indicates the number is a fixed-line number.  There
	// have been plans to migrate fixed-line numbers to start with the digit two
	// since December 2000, but it has not happened yet. See
	// http://en.wikipedia.org/wiki/%2B39 for more details.
	//
	// These fields can be safely ignored (there is no need to set them) for most
	// countries. Some limited number of countries behave like Italy - for these
	// cases, if the leading zero(s) of a number would be retained even when
	// dialling internationally, set this flag to true, and also set the number of
	// leading zeros.
	//
	// Clients who use the parsing functionality of the i18n phone
	// number libraries will have these fields set if necessary automatically.
	ItalianLeadingZero   *bool  `protobuf:"varint,4,opt,name=italian_leading_zero,json=italianLeadingZero" json:"italian_leading_zero,omitempty"`
	NumberOfLeadingZeros *int32 `protobuf:"varint,8,opt,name=number_of_leading_zeros,json=numberOfLeadingZeros,def=1" json:"number_of_leading_zeros,omitempty"`
	// This field is used to store the raw input string containing phone numbers
	// before it was canonicalized by the library. For example, it could be used
	// to store alphanumerical numbers such as "1-800-GOOG-411".
	RawInput *string `protobuf:"bytes,5,opt,name=raw_input,json=rawInput" json:"raw_input,omitempty"`
	// The source from which the country_code is derived.
	CountryCodeSource *PhoneNumber_CountryCodeSource `` /* 161-byte string literal not displayed */
	// The carrier selection code that is preferred when calling this phone number
	// domestically. This also includes codes that need to be dialed in some
	// countries when calling from landlines to mobiles or vice versa. For
	// example, in Columbia, a "3" needs to be dialed before the phone number
	// itself when calling from a mobile phone to a domestic landline phone and
	// vice versa.
	//
	// Note this is the "preferred" code, which means other codes may work as
	// well.
	PreferredDomesticCarrierCode *string `` /* 142-byte string literal not displayed */
	XXX_unrecognized             []byte  `json:"-"`
}

func GetExampleNumber

func GetExampleNumber(regionCode string) *PhoneNumber

Gets a valid number for the specified region.

func GetExampleNumberForNonGeoEntity

func GetExampleNumberForNonGeoEntity(countryCallingCode int) *PhoneNumber

Gets a valid number for the specified country calling code for a non-geographical entity.

func GetExampleNumberForType

func GetExampleNumberForType(regionCode string, typ PhoneNumberType) *PhoneNumber

Gets a valid number for the specified region and number type.

func Parse

func Parse(numberToParse, defaultRegion string) (*PhoneNumber, error)

Parses a string and returns it in proto buffer format. This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with IsValidNumber().

func ParseAndKeepRawInput

func ParseAndKeepRawInput(
	numberToParse, defaultRegion string) (*PhoneNumber, error)

Parses a string and returns it in proto buffer format. This method differs from Parse() in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.

func (*PhoneNumber) Descriptor

func (*PhoneNumber) Descriptor() ([]byte, []int)

func (*PhoneNumber) GetCountryCode

func (m *PhoneNumber) GetCountryCode() int32

func (*PhoneNumber) GetCountryCodeSource

func (m *PhoneNumber) GetCountryCodeSource() PhoneNumber_CountryCodeSource

func (*PhoneNumber) GetExtension

func (m *PhoneNumber) GetExtension() string

func (*PhoneNumber) GetItalianLeadingZero

func (m *PhoneNumber) GetItalianLeadingZero() bool

func (*PhoneNumber) GetNationalNumber

func (m *PhoneNumber) GetNationalNumber() uint64

func (*PhoneNumber) GetNumberOfLeadingZeros

func (m *PhoneNumber) GetNumberOfLeadingZeros() int32

func (*PhoneNumber) GetPreferredDomesticCarrierCode

func (m *PhoneNumber) GetPreferredDomesticCarrierCode() string

func (*PhoneNumber) GetRawInput

func (m *PhoneNumber) GetRawInput() string

func (*PhoneNumber) ProtoMessage

func (*PhoneNumber) ProtoMessage()

func (*PhoneNumber) Reset

func (m *PhoneNumber) Reset()

func (*PhoneNumber) String

func (m *PhoneNumber) String() string

type PhoneNumberDesc

type PhoneNumberDesc struct {
	// The national_number_pattern is the pattern that a valid national
	// significant number would match. This specifies information such as its
	// total length and leading digits.
	NationalNumberPattern *string `protobuf:"bytes,2,opt,name=national_number_pattern,json=nationalNumberPattern" json:"national_number_pattern,omitempty"`
	// These represent the lengths a phone number from this region can be. They
	// will be sorted from smallest to biggest. Note that these lengths are for
	// the full number, without country calling code or national prefix. For
	// example, for the Swiss number +41789270000, in local format 0789270000,
	// this would be 9.
	// This could be used to highlight tokens in a text that may be a phone
	// number, or to quickly prune numbers that could not possibly be a phone
	// number for this locale.
	PossibleLength []int32 `protobuf:"varint,9,rep,name=possible_length,json=possibleLength" json:"possible_length,omitempty"`
	// These represent the lengths that only local phone numbers (without an area
	// code) from this region can be. They will be sorted from smallest to
	// biggest. For example, since the American number 456-1234 may be locally
	// diallable, although not diallable from outside the area, 7 could be a
	// possible value.
	// This could be used to highlight tokens in a text that may be a phone
	// number.
	// To our knowledge, area codes are usually only relevant for some fixed-line
	// and mobile numbers, so this field should only be set for those types of
	// numbers (and the general description) - however there are exceptions for
	// NANPA countries.
	// This data is used to calculate whether a number could be a possible number
	// for a particular type.
	PossibleLengthLocalOnly []int32 `` /* 129-byte string literal not displayed */
	// An example national significant number for the specific type. It should
	// not contain any formatting information.
	ExampleNumber    *string `protobuf:"bytes,6,opt,name=example_number,json=exampleNumber" json:"example_number,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

If you add, remove, or rename fields, or change their semantics, check if you should change the excludable field sets or the behavior in MetadataFilter.

func (*PhoneNumberDesc) Descriptor

func (*PhoneNumberDesc) Descriptor() ([]byte, []int)

func (*PhoneNumberDesc) GetExampleNumber

func (m *PhoneNumberDesc) GetExampleNumber() string

func (*PhoneNumberDesc) GetNationalNumberPattern

func (m *PhoneNumberDesc) GetNationalNumberPattern() string

func (*PhoneNumberDesc) GetPossibleLength

func (m *PhoneNumberDesc) GetPossibleLength() []int32

func (*PhoneNumberDesc) GetPossibleLengthLocalOnly

func (m *PhoneNumberDesc) GetPossibleLengthLocalOnly() []int32

func (*PhoneNumberDesc) ProtoMessage

func (*PhoneNumberDesc) ProtoMessage()

func (*PhoneNumberDesc) Reset

func (m *PhoneNumberDesc) Reset()

func (*PhoneNumberDesc) String

func (m *PhoneNumberDesc) String() string

type PhoneNumberFormat

type PhoneNumberFormat int
const (
	E164 PhoneNumberFormat = iota
	INTERNATIONAL
	NATIONAL
	RFC3966
)

type PhoneNumberMatcher

type PhoneNumberMatcher struct {
}

func NewPhoneNumberMatcher

func NewPhoneNumberMatcher(seq string) *PhoneNumberMatcher

type PhoneNumberType

type PhoneNumberType int
const (
	// NOTES:
	//
	// FIXED_LINE_OR_MOBILE:
	//     In some regions (e.g. the USA), it is impossible to distinguish
	//     between fixed-line and mobile numbers by looking at the phone
	//     number itself.
	// SHARED_COST:
	//     The cost of this call is shared between the caller and the
	//     recipient, and is hence typically less than PREMIUM_RATE calls.
	//     See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
	//     more information.
	// VOIP:
	//     Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
	// PERSONAL_NUMBER:
	//     A personal number is associated with a particular person, and may
	//     be routed to either a MOBILE or FIXED_LINE number. Some more
	//     information can be found here:
	//     http://en.wikipedia.org/wiki/Personal_Numbers
	// UAN:
	//     Used for "Universal Access Numbers" or "Company Numbers". They
	//     may be further routed to specific offices, but allow one number
	//     to be used for a company.
	// VOICEMAIL:
	//     Used for "Voice Mail Access Numbers".
	// UNKNOWN:
	//     A phone number is of type UNKNOWN when it does not fit any of
	// the known patterns for a specific region.
	FIXED_LINE PhoneNumberType = iota
	MOBILE
	FIXED_LINE_OR_MOBILE
	TOLL_FREE
	PREMIUM_RATE
	SHARED_COST
	VOIP
	PERSONAL_NUMBER
	PAGER
	UAN
	VOICEMAIL
	UNKNOWN
)

func GetNumberType

func GetNumberType(number *PhoneNumber) PhoneNumberType

Gets the type of a phone number.

type PhoneNumber_CountryCodeSource

type PhoneNumber_CountryCodeSource int32

The source from which the country_code is derived. This is not set in the general parsing method, but in the method that parses and keeps raw_input. New fields could be added upon request.

const (
	// Default value returned if this is not set, because the phone number was
	// created using parse, not parseAndKeepRawInput. hasCountryCodeSource will
	// return false if this is the case.
	PhoneNumber_UNSPECIFIED PhoneNumber_CountryCodeSource = 0
	// The country_code is derived based on a phone number with a leading "+",
	// e.g. the French number "+33 1 42 68 53 00".
	PhoneNumber_FROM_NUMBER_WITH_PLUS_SIGN PhoneNumber_CountryCodeSource = 1
	// The country_code is derived based on a phone number with a leading IDD,
	// e.g. the French number "011 33 1 42 68 53 00", as it is dialled from US.
	PhoneNumber_FROM_NUMBER_WITH_IDD PhoneNumber_CountryCodeSource = 5
	// The country_code is derived based on a phone number without a leading
	// "+", e.g. the French number "33 1 42 68 53 00" when defaultCountry is
	// supplied as France.
	PhoneNumber_FROM_NUMBER_WITHOUT_PLUS_SIGN PhoneNumber_CountryCodeSource = 10
	// The country_code is derived NOT based on the phone number itself, but
	// from the defaultCountry parameter provided in the parsing function by the
	// clients. This happens mostly for numbers written in the national format
	// (without country code). For example, this would be set when parsing the
	// French number "01 42 68 53 00", when defaultCountry is supplied as
	// France.
	PhoneNumber_FROM_DEFAULT_COUNTRY PhoneNumber_CountryCodeSource = 20
)

func (PhoneNumber_CountryCodeSource) Enum

func (PhoneNumber_CountryCodeSource) EnumDescriptor

func (PhoneNumber_CountryCodeSource) EnumDescriptor() ([]byte, []int)

func (PhoneNumber_CountryCodeSource) String

func (*PhoneNumber_CountryCodeSource) UnmarshalJSON

func (x *PhoneNumber_CountryCodeSource) UnmarshalJSON(data []byte) error

type ValidationResult

type ValidationResult int
const (
	IS_POSSIBLE ValidationResult = iota
	INVALID_COUNTRY_CODE
	TOO_SHORT
	TOO_LONG
)

func IsPossibleNumberWithReason

func IsPossibleNumberWithReason(number *PhoneNumber) ValidationResult

Check whether a phone number is a possible number. It provides a more lenient check than IsValidNumber() in the following sense:

  • It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
  • It doesn't attempt to figure out the type of the number, but uses general rules which applies to all types of phone numbers in a region. Therefore, it is much faster than isValidNumber.
  • For fixed line numbers, many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial the subscriber number only when dialing in the same area. This function will return true if the subscriber-number-only version is passed in. On the other hand, because isValidNumber validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL