phonenumbers

package module
v1.3.4 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2024 License: MIT Imports: 23 Imported by: 233

README

phonenumbers

Build Status codecov GoDoc

golang port of Google's libphonenumber, forked from libphonenumber from ttacon which in turn is a port of the original Java library.

You can see a live demo of the number parsing of the master branch of this library at https://phonenumbers.temba.io/ Compare results with the official Google Java version.

This fork fixes quite a few bugs and more closely follows the official Java implementation. It also adds the buildmetadata cmd to allow for rebuilding the metadata protocol buffers, country code to region maps and timezone prefix maps. We keep this library up to date with the upstream Google repo as metadata changes take place, usually no more than a few days behind official Google releases.

This library is used daily in production for parsing and validation of numbers across the world, so is well maintained. Please open an issue if you encounter any problems, we'll do our best to address them.

Version Numbers

As we don't want to bump our major semantic version number in step with the upstream library, we use independent version numbers than the Google libphonenumber repo. The release notes will mention what version of the metadata a release was built against.

Usage

// parse our phone number
num, err := phonenumbers.Parse("6502530000", "US")

// format it using national format
formattedNum := phonenumbers.Format(num, phonenumbers.NATIONAL)

Rebuilding Metadata and Maps

The buildmetadata command will fetch the latest XML file from the official Google repo and rebuild the go source files containing all the territory metadata, timezone and region maps.

It will rebuild the following files:

  • gen/metadata_bin.go - protocol buffer definitions for all the various formats across countries etc..
  • gen/shortnumber_metadata_bin.go - protocol buffer definitions for ShortNumberMetadata.xml
  • gen/countrycode_to_region_bin.go - information needed to map a contry code to a region
  • gen/prefix_to_carrier_bin.go - information needed to map a phone number prefix to a carrier
  • gen/prefix_to_geocoding_bin.go - information needed to map a phone number prefix to a city or region
  • gen/prefix_to_timezone_bin.go - information needed to map a phone number prefix to a city or region
% go install github.com/nyaruka/phonenumbers/cmd/buildmetadata
% $GOPATH/bin/buildmetadata

Documentation

Index

Constants

View Source
const (
	Default_PhoneMetadata_SameMobileAndFixedLinePattern = bool(false)
	Default_PhoneMetadata_MainCountryForCode            = bool(false)
	Default_PhoneMetadata_LeadingZeroPossible           = bool(false)
	Default_PhoneMetadata_MobileNumberPortableRegion    = bool(false)
)

Default values for PhoneMetadata fields.

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)
)

Default values for NumberFormat fields.

View Source
const (
	Default_PhoneNumber_NumberOfLeadingZeros = int32(1)
)

Default values for PhoneNumber fields.

Variables

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

Enum value maps for PhoneNumber_CountryCodeSource.

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"

	// Regular expression of valid global-number-digits for the phone-context parameter, following the
	// syntax defined in RFC3966.
	RFC3966_VISUAL_SEPARATOR             = "[\\-\\.\\(\\)]?"
	RFC3966_PHONE_DIGIT                  = "(" + DIGITS + "|" + RFC3966_VISUAL_SEPARATOR + ")"
	RFC3966_GLOBAL_NUMBER_DIGITS         = "^\\" + string(PLUS_SIGN) + RFC3966_PHONE_DIGIT + "*" + DIGITS + RFC3966_PHONE_DIGIT + "*$"
	RFC3966_GLOBAL_NUMBER_DIGITS_PATTERN = regexp.MustCompile(RFC3966_GLOBAL_NUMBER_DIGITS)

	// Regular expression of valid domainname for the phone-context parameter, following the syntax
	// defined in RFC3966.
	ALPHANUM                   = VALID_ALPHA + DIGITS
	RFC3966_DOMAINLABEL        = "[" + ALPHANUM + "]+((\\-)*[" + ALPHANUM + "])*"
	RFC3966_TOPLABEL           = "[" + VALID_ALPHA + "]+((\\-)*[" + ALPHANUM + "])*"
	RFC3966_DOMAINNAME         = "^(" + RFC3966_DOMAINLABEL + "\\.)*" + RFC3966_TOPLABEL + "\\.?$"
	RFC3966_DOMAINNAME_PATTERN = regexp.MustCompile(RFC3966_DOMAINNAME)
)
View Source
var (
	ErrInvalidCountryCode = errors.New("invalid country code")
	ErrNotANumber         = errors.New("the phone number supplied is not a number")
	ErrTooShortNSN        = errors.New("the string supplied is too short to be a phone number")
)
View Source
var ErrEmptyMetadata = errors.New("empty metadata")
View Source
var ErrFailedToGrow = errors.New("insertablebuffer.Buf: failed to grow buffer enough")
View Source
var ErrInvalidIndex = errors.New("insertablebuffer.Buf: invalid index")
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 File_phonemetadata_proto protoreflect.FileDescriptor
View Source
var File_phonenumber_proto protoreflect.FileDescriptor

Functions

func AllNumberGroupsAreExactlyPresent

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

func AllNumberGroupsRemainGrouped

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

func BuildCountryCodeToRegionMap

func BuildCountryCodeToRegionMap(metadataCollection *PhoneMetadataCollection) map[int][]string

Build a mapping from a country calling code to the region codes which denote the country/region represented by that country code. In the case of multiple countries sharing a calling code, such as the NANPA countries, the one indicated with "isMainCountryForCode" in the metadata should be first.

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

FormatByPattern 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)

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

func GetCarrierForNumber added in v1.0.22

func GetCarrierForNumber(number *PhoneNumber, lang string) (string, error)

GetCarrierForNumber returns the carrier we believe the number belongs to. Note due to number porting this is only a guess, there is no guarantee to its accuracy.

func GetCarrierWithPrefixForNumber added in v1.0.68

func GetCarrierWithPrefixForNumber(number *PhoneNumber, lang string) (string, int, error)

GetCarrierWithPrefixForNumber returns the carrier we believe the number belongs to, as well as its prefix. Note due to number porting this is only a guess, there is no guarantee to its accuracy.

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 GetGeocodingForNumber added in v1.0.22

func GetGeocodingForNumber(number *PhoneNumber, lang string) (string, error)

GetGeocodingForNumber returns the location we think the number was first acquired in. This is just our best guess, there is no guarantee to its accuracy.

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 GetSafeCarrierDisplayNameForNumber added in v1.2.0

func GetSafeCarrierDisplayNameForNumber(phoneNumber *PhoneNumber, lang string) (string, error)

GetSafeCarrierDisplayNameForNumber Gets the name of the carrier for the given phone number only when it is 'safe' to display to users. A carrier name is considered safe if the number is valid and for a region that doesn't support mobile number portability .

func GetSupportedCallingCodes added in v1.0.23

func GetSupportedCallingCodes() map[int]bool

GetSupportedCallingCodes returns all country calling codes the library has metadata for, covering both non-geographical entities (global network calling codes) and those used for geographical entities. This could be used to populate a drop-down box of country calling codes for a phone-number widget, for instance.

func GetSupportedGlobalNetworkCallingCodes

func GetSupportedGlobalNetworkCallingCodes() map[int]bool

GetSupportedGlobalNetworkCallingCodes returns all global network calling codes the library has metadata for.

func GetSupportedRegions

func GetSupportedRegions() map[string]bool

GetSupportedRegions returns all regions the library has metadata for.

func GetTimezonesForNumber added in v1.0.22

func GetTimezonesForNumber(number *PhoneNumber) ([]string, error)

GetTimezonesForNumber returns the names of timezones which we believe maps to the passed in number.

func GetTimezonesForPrefix

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

GetTimezonesForPrefix 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 IsPossibleShortNumber added in v1.1.0

func IsPossibleShortNumber(number *PhoneNumber) bool

Check whether a short number is a possible number. If a country calling code is shared by multiple regions, this returns true if it's possible in any of them. This provides a more lenient check than #isValidShortNumber. See IsPossibleShortNumberForRegion(PhoneNumber, string) for details.

func IsPossibleShortNumberForRegion added in v1.1.0

func IsPossibleShortNumberForRegion(number *PhoneNumber, regionDialingFrom string) bool

Check whether a short number is a possible number when dialed from the given region. This provides a more lenient check than IsValidShortNumberForRegion.

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 IsValidShortNumber added in v1.1.0

func IsValidShortNumber(number *PhoneNumber) bool

Tests whether a short number matches a valid pattern. If a country calling code is shared by multiple regions, this returns true if it's valid in any of them. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. See IsValidShortNumberForRegion(PhoneNumber, String) for details.

func IsValidShortNumberForRegion added in v1.1.0

func IsValidShortNumberForRegion(number *PhoneNumber, regionDialingFrom string) bool

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

func MatchNationalNumber added in v1.1.0

func MatchNationalNumber(number string, numberDesc PhoneNumberDesc, allowPrefixMatch bool) bool

Returns whether the given national number (a string containing only decimal digits) matches the national number pattern defined in the given PhoneNumberDesc message.

func MaybeSeparateExtensionFromPhone added in v1.0.61

func MaybeSeparateExtensionFromPhone(rawPhone string) (phoneNumber string, extension string)

MaybeSeparateExtensionFromPhone will extract any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number and returns it along with the proceeding phone number. The phone number will maintain its original formatting including alpha characters.

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 Builder

type Builder struct {
	// contains filtered or unexported fields
}

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

func NewBuilder

func NewBuilder(buf []byte) *Builder

NewBuilder creates and initializes a new Buffer using buf as its initial contents. It is intended to prepare a Buffer to read existing data. It can also be used to size the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func NewBuilderString

func NewBuilderString(s string) *Builder

NewBuilderString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func (*Builder) ByteAt

func (b *Builder) ByteAt(i int) (byte, error)

ByteAt returns the byte at the given index. It returns ErrInvalidIndex if the given index is outside the buffer's length. There is no RuneAt currently, for I'm unsure what the desired behaviour should be (read rune by rune until we get to the ith rune, read the rune starting at i).

func (*Builder) Bytes

func (b *Builder) Bytes() []byte

Bytes returns a slice of the contents of the unread portion of the buffer; len(b.Bytes()) == b.Len(). If the caller changes the contents of the returned slice, the contents of the buffer will change provided there are no intervening method calls on the Buffer.

func (*Builder) Grow

func (b *Builder) Grow(n int)

Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. If n is negative, Grow will panic. If the buffer can't grow it will panic with ErrTooLarge.

func (*Builder) Insert

func (b *Builder) Insert(i int, p []byte) (n int, err error)

Insert inserts the buffer at the desired position, growing the buffer as necessary. If i is less than zero, or greater than len(p), an error is returned.

func (*Builder) InsertString

func (b *Builder) InsertString(i int, p string) (n int, err error)

InsertString inserts the string at the desired position, growing the buffer as necessary. If i is less than zero, or greater than len(p), an error is returned.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

func (*Builder) Next

func (b *Builder) Next(n int) []byte

Next returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.

func (*Builder) Read

func (b *Builder) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

func (*Builder) ReadByte

func (b *Builder) ReadByte() (c byte, err error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.

func (*Builder) ReadBytes

func (b *Builder) ReadBytes(delim byte) (line []byte, err error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.

func (*Builder) ReadFrom

func (b *Builder) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

func (*Builder) ReadRune

func (b *Builder) ReadRune() (r rune, size int, err error)

ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

func (*Builder) ReadString

func (b *Builder) ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

func (*Builder) Reset

func (b *Builder) Reset()

Reset resets the buffer so it has no content. b.Reset() is the same as b.Truncate(0).

func (*Builder) ResetWith

func (b *Builder) ResetWith(buf []byte) (n int, err error)

func (*Builder) ResetWithString

func (b *Builder) ResetWithString(s string) (n int, err error)

func (*Builder) String

func (b *Builder) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

func (*Builder) Truncate

func (b *Builder) Truncate(n int)

Truncate discards all but the first n unread bytes from the buffer. It panics if n is negative or greater than the length of the buffer.

func (*Builder) UnreadByte

func (b *Builder) UnreadByte() error

UnreadByte unreads the last byte returned by the most recent read operation. If write has happened since the last read, UnreadByte returns an error.

func (*Builder) UnreadRune

func (b *Builder) UnreadRune() error

UnreadRune unreads the last rune returned by ReadRune. If the most recent read or write operation on the buffer was not a ReadRune, UnreadRune returns an error. (In this regard it is stricter than UnreadByte, which will unread the last byte from any read operation.)

func (*Builder) Write

func (b *Builder) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) error

WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. If the buffer becomes too large, WriteByte will panic with ErrTooLarge.

func (*Builder) WriteRune

func (b *Builder) WriteRune(r rune) (n int, err error)

WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic with ErrTooLarge.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) (n int, err error)

WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. If the buffer becomes too large, WriteString will panic with ErrTooLarge.

func (*Builder) WriteTo

func (b *Builder) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.

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.

func IsNumberMatchWithNumbers added in v1.0.65

func IsNumberMatchWithNumbers(firstNumberIn, secondNumberIn *PhoneNumber) MatchType

Takes two phone numbers and compares them for equality.

Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. Returns NO_MATCH otherwise. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.

func IsNumberMatchWithOneNumber added in v1.0.65

func IsNumberMatchWithOneNumber(
	firstNumber *PhoneNumber, secondNumber string) MatchType

Takes two phone numbers 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 */
	// contains filtered or unexported fields
}

func (*NumberFormat) Descriptor deprecated

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

Deprecated: Use NumberFormat.ProtoReflect.Descriptor instead.

func (*NumberFormat) GetDomesticCarrierCodeFormattingRule

func (x *NumberFormat) GetDomesticCarrierCodeFormattingRule() string

func (*NumberFormat) GetFormat

func (x *NumberFormat) GetFormat() string

func (*NumberFormat) GetLeadingDigitsPattern

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

func (*NumberFormat) GetNationalPrefixFormattingRule

func (x *NumberFormat) GetNationalPrefixFormattingRule() string

func (*NumberFormat) GetNationalPrefixOptionalWhenFormatting

func (x *NumberFormat) GetNationalPrefixOptionalWhenFormatting() bool

func (*NumberFormat) GetPattern

func (x *NumberFormat) GetPattern() string

func (*NumberFormat) ProtoMessage

func (*NumberFormat) ProtoMessage()

func (*NumberFormat) ProtoReflect added in v1.2.1

func (x *NumberFormat) ProtoReflect() protoreflect.Message

func (*NumberFormat) Reset

func (x *NumberFormat) Reset()

func (*NumberFormat) String

func (x *NumberFormat) String() string

type NumberFormatE

type NumberFormatE struct {
	// <!ELEMENT leadingDigits (#PCDATA)>
	LeadingDigits []string `xml:"leadingDigits"`

	// <!ELEMENT format (#PCDATA)>
	Format string `xml:"format"`

	// <!ELEMENT intlFormat (#PCDATA)>
	InternationalFormat []string `xml:"intlFormat"`

	// <!ATTLIST numberFormat nationalPrefixFormattingRule CDATA #IMPLIED>
	NationalPrefixFormattingRule string `xml:"nationalPrefixFormattingRule,attr"`

	// <!ATTLIST numberFormat nationalPrefixOptionalWhenFormatting (true) #IMPLIED>
	NationalPrefixOptionalWhenFormatting *bool `xml:"nationalPrefixOptionalWhenFormatting,attr"`

	// <!ATTLIST numberFormat carrierCodeFormattingRule CDATA #IMPLIED>
	CarrierCodeFormattingRule string `xml:"carrierCodeFormattingRule,attr"`

	// <!ATTLIST numberFormat pattern CDATA #REQUIRED>
	Pattern string `xml:"pattern,attr" validate:"required"`
}

<!ELEMENT numberFormat (leadingDigits*, format, intlFormat*)>

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 */
	// contains filtered or unexported fields
}

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 deprecated

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

Deprecated: Use PhoneMetadata.ProtoReflect.Descriptor instead.

func (*PhoneMetadata) GetCarrierSpecific

func (x *PhoneMetadata) GetCarrierSpecific() *PhoneNumberDesc

func (*PhoneMetadata) GetCountryCode

func (x *PhoneMetadata) GetCountryCode() int32

func (*PhoneMetadata) GetEmergency

func (x *PhoneMetadata) GetEmergency() *PhoneNumberDesc

func (*PhoneMetadata) GetFixedLine

func (x *PhoneMetadata) GetFixedLine() *PhoneNumberDesc

func (*PhoneMetadata) GetGeneralDesc

func (x *PhoneMetadata) GetGeneralDesc() *PhoneNumberDesc

func (*PhoneMetadata) GetId

func (x *PhoneMetadata) GetId() string

func (*PhoneMetadata) GetInternationalPrefix

func (x *PhoneMetadata) GetInternationalPrefix() string

func (*PhoneMetadata) GetIntlNumberFormat

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

func (*PhoneMetadata) GetLeadingDigits

func (x *PhoneMetadata) GetLeadingDigits() string

func (*PhoneMetadata) GetLeadingZeroPossible

func (x *PhoneMetadata) GetLeadingZeroPossible() bool

func (*PhoneMetadata) GetMainCountryForCode

func (x *PhoneMetadata) GetMainCountryForCode() bool

func (*PhoneMetadata) GetMobile

func (x *PhoneMetadata) GetMobile() *PhoneNumberDesc

func (*PhoneMetadata) GetMobileNumberPortableRegion

func (x *PhoneMetadata) GetMobileNumberPortableRegion() bool

func (*PhoneMetadata) GetNationalPrefix

func (x *PhoneMetadata) GetNationalPrefix() string

func (*PhoneMetadata) GetNationalPrefixForParsing

func (x *PhoneMetadata) GetNationalPrefixForParsing() string

func (*PhoneMetadata) GetNationalPrefixTransformRule

func (x *PhoneMetadata) GetNationalPrefixTransformRule() string

func (*PhoneMetadata) GetNoInternationalDialling

func (x *PhoneMetadata) GetNoInternationalDialling() *PhoneNumberDesc

func (*PhoneMetadata) GetNumberFormat

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

func (*PhoneMetadata) GetPager

func (x *PhoneMetadata) GetPager() *PhoneNumberDesc

func (*PhoneMetadata) GetPersonalNumber

func (x *PhoneMetadata) GetPersonalNumber() *PhoneNumberDesc

func (*PhoneMetadata) GetPreferredExtnPrefix

func (x *PhoneMetadata) GetPreferredExtnPrefix() string

func (*PhoneMetadata) GetPreferredInternationalPrefix

func (x *PhoneMetadata) GetPreferredInternationalPrefix() string

func (*PhoneMetadata) GetPremiumRate

func (x *PhoneMetadata) GetPremiumRate() *PhoneNumberDesc

func (*PhoneMetadata) GetSameMobileAndFixedLinePattern

func (x *PhoneMetadata) GetSameMobileAndFixedLinePattern() bool

func (*PhoneMetadata) GetSharedCost

func (x *PhoneMetadata) GetSharedCost() *PhoneNumberDesc

func (*PhoneMetadata) GetShortCode

func (x *PhoneMetadata) GetShortCode() *PhoneNumberDesc

func (*PhoneMetadata) GetSmsServices added in v1.0.25

func (x *PhoneMetadata) GetSmsServices() *PhoneNumberDesc

func (*PhoneMetadata) GetStandardRate

func (x *PhoneMetadata) GetStandardRate() *PhoneNumberDesc

func (*PhoneMetadata) GetTollFree

func (x *PhoneMetadata) GetTollFree() *PhoneNumberDesc

func (*PhoneMetadata) GetUan

func (x *PhoneMetadata) GetUan() *PhoneNumberDesc

func (*PhoneMetadata) GetVoicemail

func (x *PhoneMetadata) GetVoicemail() *PhoneNumberDesc

func (*PhoneMetadata) GetVoip

func (x *PhoneMetadata) GetVoip() *PhoneNumberDesc

func (*PhoneMetadata) ProtoMessage

func (*PhoneMetadata) ProtoMessage()

func (*PhoneMetadata) ProtoReflect added in v1.2.1

func (x *PhoneMetadata) ProtoReflect() protoreflect.Message

func (*PhoneMetadata) Reset

func (x *PhoneMetadata) Reset()

func (*PhoneMetadata) String

func (x *PhoneMetadata) String() string

type PhoneMetadataCollection

type PhoneMetadataCollection struct {
	Metadata []*PhoneMetadata `protobuf:"bytes,1,rep,name=metadata" json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

func BuildPhoneMetadataCollection

func BuildPhoneMetadataCollection(inputXML []byte, liteBuild bool, specialBuild bool, isShortNumberMetadata bool) (*PhoneMetadataCollection, error)

func MetadataCollection

func MetadataCollection() (*PhoneMetadataCollection, error)

func ShortNumberMetadataCollection added in v1.1.0

func ShortNumberMetadataCollection() (*PhoneMetadataCollection, error)

func (*PhoneMetadataCollection) Descriptor deprecated

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

Deprecated: Use PhoneMetadataCollection.ProtoReflect.Descriptor instead.

func (*PhoneMetadataCollection) GetMetadata

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

func (*PhoneMetadataCollection) ProtoMessage

func (*PhoneMetadataCollection) ProtoMessage()

func (*PhoneMetadataCollection) ProtoReflect added in v1.2.1

func (x *PhoneMetadataCollection) ProtoReflect() protoreflect.Message

func (*PhoneMetadataCollection) Reset

func (x *PhoneMetadataCollection) Reset()

func (*PhoneMetadataCollection) String

func (x *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 `` /* 156-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 */
	// contains filtered or unexported fields
}

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 deprecated

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

Deprecated: Use PhoneNumber.ProtoReflect.Descriptor instead.

func (*PhoneNumber) GetCountryCode

func (x *PhoneNumber) GetCountryCode() int32

func (*PhoneNumber) GetCountryCodeSource

func (x *PhoneNumber) GetCountryCodeSource() PhoneNumber_CountryCodeSource

func (*PhoneNumber) GetExtension

func (x *PhoneNumber) GetExtension() string

func (*PhoneNumber) GetItalianLeadingZero

func (x *PhoneNumber) GetItalianLeadingZero() bool

func (*PhoneNumber) GetNationalNumber

func (x *PhoneNumber) GetNationalNumber() uint64

func (*PhoneNumber) GetNumberOfLeadingZeros

func (x *PhoneNumber) GetNumberOfLeadingZeros() int32

func (*PhoneNumber) GetPreferredDomesticCarrierCode

func (x *PhoneNumber) GetPreferredDomesticCarrierCode() string

func (*PhoneNumber) GetRawInput

func (x *PhoneNumber) GetRawInput() string

func (*PhoneNumber) ProtoMessage

func (*PhoneNumber) ProtoMessage()

func (*PhoneNumber) ProtoReflect added in v1.2.1

func (x *PhoneNumber) ProtoReflect() protoreflect.Message

func (*PhoneNumber) Reset

func (x *PhoneNumber) Reset()

func (*PhoneNumber) String

func (x *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"`
	// contains filtered or unexported fields
}

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 deprecated

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

Deprecated: Use PhoneNumberDesc.ProtoReflect.Descriptor instead.

func (*PhoneNumberDesc) GetExampleNumber

func (x *PhoneNumberDesc) GetExampleNumber() string

func (*PhoneNumberDesc) GetNationalNumberPattern

func (x *PhoneNumberDesc) GetNationalNumberPattern() string

func (*PhoneNumberDesc) GetPossibleLength

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

func (*PhoneNumberDesc) GetPossibleLengthLocalOnly

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

func (*PhoneNumberDesc) ProtoMessage

func (*PhoneNumberDesc) ProtoMessage()

func (*PhoneNumberDesc) ProtoReflect added in v1.2.1

func (x *PhoneNumberDesc) ProtoReflect() protoreflect.Message

func (*PhoneNumberDesc) Reset

func (x *PhoneNumberDesc) Reset()

func (*PhoneNumberDesc) String

func (x *PhoneNumberDesc) String() string

type PhoneNumberDescE

type PhoneNumberDescE struct {
	// <!ELEMENT nationalNumberPattern (#PCDATA)>
	NationalNumberPattern string `xml:"nationalNumberPattern"`

	// <!ELEMENT possibleLengths EMPTY>
	PossibleLengths *PossibleLengthE `xml:"possibleLengths"`

	// <!ELEMENT exampleNumber (#PCDATA)>
	ExampleNumber string `xml:"exampleNumber"`
}

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 PhoneNumberMetadataE

type PhoneNumberMetadataE struct {
	// <!ELEMENT territories (territory+)>
	Territories []TerritoryE `xml:"territories>territory"`
}

<!ELEMENT phoneNumberMetadata (territories)>

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) Descriptor added in v1.2.1

func (PhoneNumber_CountryCodeSource) Enum

func (PhoneNumber_CountryCodeSource) EnumDescriptor deprecated

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

Deprecated: Use PhoneNumber_CountryCodeSource.Descriptor instead.

func (PhoneNumber_CountryCodeSource) Number added in v1.2.1

func (PhoneNumber_CountryCodeSource) String

func (PhoneNumber_CountryCodeSource) Type added in v1.2.1

func (*PhoneNumber_CountryCodeSource) UnmarshalJSON deprecated

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

Deprecated: Do not use.

type PossibleLengthE

type PossibleLengthE struct {
	// <!ATTLIST possibleLengths national CDATA #REQUIRED>
	National string `xml:"national,attr"`

	// <!ATTLIST possibleLengths localOnly CDATA #IMPLIED>
	LocalOnly string `xml:"localOnly,attr"`
}

type TerritoryE

type TerritoryE struct {
	// <!ATTLIST territory id CDATA #REQUIRED>
	ID string `xml:"id,attr"`

	// <!ATTLIST territory mainCountryForCode (true) #IMPLIED>
	MainCountryForCode bool `xml:"mainCountryForCode,attr"`

	// <!ATTLIST territory leadingDigits CDATA #IMPLIED>
	LeadingDigits string `xml:"leadingDigits,attr"`

	// <!ATTLIST territory countryCode CDATA #REQUIRED>
	CountryCode int32 `xml:"countryCode,attr"`

	// <!ATTLIST territory nationalPrefix CDATA #IMPLIED>
	NationalPrefix string `xml:"nationalPrefix,attr"`

	// <!ATTLIST territory internationalPrefix CDATA #IMPLIED>
	InternationalPrefix string `xml:"internationalPrefix,attr"`

	// <!ATTLIST territory preferredInternationalPrefix CDATA #IMPLIED>
	PreferredInternationalPrefix string `xml:"preferredInternationalPrefix,attr"`

	// <!ATTLIST territory nationalPrefixFormattingRule CDATA #IMPLIED>
	NationalPrefixFormattingRule string `xml:"nationalPrefixFormattingRule,attr"`

	// <!ATTLIST territory mobileNumberPortableRegion (true) #IMPLIED>
	MobileNumberPortableRegion bool `xml:"mobileNumberPortableRegion,attr"`

	// <!ATTLIST territory nationalPrefixForParsing CDATA #IMPLIED>
	NationalPrefixForParsing string `xml:"nationalPrefixForParsing,attr"`

	// <!ATTLIST territory nationalPrefixTransformRule CDATA #IMPLIED>
	NationalPrefixTransformRule string `xml:"nationalPrefixTransformRule,attr"`

	// <!ATTLIST territory preferredExtnPrefix CDATA #IMPLIED>
	PreferredExtnPrefix string `xml:"PreferredExtnPrefix"`

	// <!ATTLIST territory nationalPrefixOptionalWhenFormatting (true) #IMPLIED>
	NationalPrefixOptionalWhenFormatting bool `xml:"nationalPrefixOptionalWhenFormatting,attr"`

	// <!ATTLIST territory carrierCodeFormattingRule CDATA #IMPLIED>
	CarrierCodeFormattingRule string `xml:"carrierCodeFormattingRule,attr"`

	// <!ELEMENT references (sourceUrl+)>
	// <!ELEMENT sourceUrl (#PCDATA)>
	References []string `xml:"references>sourceUrl"`

	// <!ELEMENT availableFormats (numberFormat+)>
	AvailableFormats []NumberFormatE `xml:"availableFormats>numberFormat"`

	// <!ELEMENT generalDesc (nationalNumberPattern)>
	GeneralDesc *PhoneNumberDescE `xml:"generalDesc"`

	// <!ELEMENT noInternationalDialling (nationalNumberPattern, possibleLengths, exampleNumber)>
	NoInternationalDialing *PhoneNumberDescE `xml:"noInternationalDialing"`

	// <!ELEMENT fixedLine (nationalNumberPattern, possibleLengths, exampleNumber)>
	FixedLine *PhoneNumberDescE `xml:"fixedLine"`

	// <!ELEMENT mobile (nationalNumberPattern, possibleLengths, exampleNumber)>
	Mobile *PhoneNumberDescE `xml:"mobile"`

	// <!ELEMENT pager (nationalNumberPattern, possibleLengths, exampleNumber)>
	Pager *PhoneNumberDescE `xml:"pager"`

	// <!ELEMENT tollFree (nationalNumberPattern, possibleLengths, exampleNumber)>
	TollFree *PhoneNumberDescE `xml:"tollFree"`

	// <!ELEMENT premiumRate (nationalNumberPattern, possibleLengths, exampleNumber)>
	PremiumRate *PhoneNumberDescE `xml:"premiumRate"`

	// <!ELEMENT sharedCost (nationalNumberPattern, possibleLengths, exampleNumber)>
	SharedCost *PhoneNumberDescE `xml:"sharedCost"`

	// <!ELEMENT personalNumber (nationalNumberPattern, possibleLengths, exampleNumber)>
	PersonalNumber *PhoneNumberDescE `xml:"personalNumber"`

	// <!ELEMENT voip (nationalNumberPattern, possibleLengths, exampleNumber)>
	VOIP *PhoneNumberDescE `xml:"voip"`

	// <!ELEMENT uan (nationalNumberPattern, possibleLengths, exampleNumber)>
	UAN *PhoneNumberDescE `xml:"uan"`

	// <!ELEMENT voicemail (nationalNumberPattern, possibleLengths, exampleNumber)>
	VoiceMail *PhoneNumberDescE `xml:"voicemail"`

	// <!ELEMENT uan (nationalNumberPattern, possibleLengths, exampleNumber)>
	StandardRate *PhoneNumberDescE `xml:"standardRate"`

	// <!ELEMENT voicemail (nationalNumberPattern, possibleLengths, exampleNumber)>
	ShortCode *PhoneNumberDescE `xml:"shortCode"`

	// <!ELEMENT uan (nationalNumberPattern, possibleLengths, exampleNumber)>
	Emergency *PhoneNumberDescE `xml:"Emergency"`

	// <!ELEMENT voicemail (nationalNumberPattern, possibleLengths, exampleNumber)>
	CarrierSpecific *PhoneNumberDescE `xml:"carrierSpecific"`
}

<!ELEMENT territory (references?, availableFormats?, generalDesc, noInternationalDialling?,

fixedLine?, mobile?, pager?, tollFree?, premiumRate?,
sharedCost?, personalNumber?, voip?, uan?, voicemail?)>

type ValidationResult

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

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.

Directories

Path Synopsis
cmd
phoneparser Module
phoneserver Module

Jump to

Keyboard shortcuts

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