Documentation
¶
Overview ¶
Port of metadata/source/* alternate-formats loading from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of AsYouTypeFormatter.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of tools/.../BuildMetadataFromXml.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of carrier/PhoneNumberToCarrierMapper.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Package phonenumbers is a Go port of Google's libphonenumber for parsing, formatting, and validating international phone numbers.
It tracks the Java implementation — libphonenumber's reference implementation, of which the C++ and JavaScript versions are themselves ports. As a result, type names, method names, and tests deliberately mirror their Java counterparts (for example PhoneNumberUtil and PhoneNumberUtilTest) to keep the port easy to verify against upstream. The aim is strictly to match libphonenumber's functionality rather than to add to it.
See SYNC.md for which upstream version each ported file is reconciled against.
Port of PhoneNumberUtil.java (enums) from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of NumberParseException.java + package errors from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of geocoder/geocoding/PhoneNumberOfflineGeocoder.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of metadata/source/* + MetadataLoader from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of PhoneNumberMatch.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of PhoneNumberMatcher.java from google/libphonenumber. Methods are kept in upstream source order to ease syncing.
Port of PhoneNumberUtil.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of internal/prefixmapper/* (shared prefix lookup) from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of ShortNumberInfo.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Port of geocoder/PhoneNumberToTimeZonesMapper.java from google/libphonenumber. Functions are kept in upstream source order to ease syncing.
Index ¶
- Constants
- Variables
- func AllNumberGroupsAreExactlyPresent(number *PhoneNumber, normalizedCandidate string, ...) bool
- func AllNumberGroupsRemainGrouped(number *PhoneNumber, normalizedCandidate string, ...) bool
- func BuildCountryCodeToRegionMap(metadataCollection *PhoneMetadataCollection) map[int][]string
- func CanBeInternationallyDialled(number *PhoneNumber) bool
- func CheckNumberGroupingIsValid(number *PhoneNumber, candidate string, ...) bool
- func Clean(phone []string, defaultRegion ...string) (VerifiedNumbers, UnverifiedNumbers)
- func ConnectsToEmergencyNumber(number string, regionCode string) bool
- func ContainsMoreThanOneSlashInNationalNumber(number *PhoneNumber, candidate string) bool
- func ContainsOnlyValidXChars(number *PhoneNumber, candidate string) bool
- func ConvertAlphaCharactersInNumber(number string) string
- func CountryCodes() []string
- func CountryNames() []string
- func Currency(code string) string
- func CurrencySymbol(code string) string
- func FindNumbers(text, defaultRegion string) iter.Seq[*PhoneNumberMatch]
- func FindNumbersWithLeniency(text, defaultRegion string, leniency Leniency, maxTries int) iter.Seq[*PhoneNumberMatch]
- func Format(number *PhoneNumber, numberFormat PhoneNumberFormat) string
- func FormatByPattern(number *PhoneNumber, numberFormat PhoneNumberFormat, ...) string
- func FormatInOriginalFormat(number *PhoneNumber, regionCallingFrom string) string
- func FormatNationalNumberWithCarrierCode(number *PhoneNumber, carrierCode string) string
- func FormatNationalNumberWithPreferredCarrierCode(number *PhoneNumber, fallbackCarrierCode string) string
- func FormatNumberForMobileDialing(number *PhoneNumber, regionCallingFrom string, withFormatting bool) string
- func FormatOutOfCountryCallingNumber(number *PhoneNumber, regionCallingFrom string) string
- func FormatOutOfCountryKeepingAlphaChars(number *PhoneNumber, regionCallingFrom string) string
- func FormatWithBuf(number *PhoneNumber, numberFormat PhoneNumberFormat, ...)deprecated
- func GetCarrierForNumber(number *PhoneNumber, lang string) (string, error)
- func GetCarrierForValidNumber(number *PhoneNumber, lang string) (string, error)
- func GetCarrierWithPrefixForNumber(number *PhoneNumber, lang string) (string, int, error)
- func GetCountryCodeForRegion(regionCode string) int
- func GetCountryMobileToken(countryCallingCode int) string
- func GetGeocodingForNumber(number *PhoneNumber, lang string) (string, error)
- func GetLengthOfGeographicalAreaCode(number *PhoneNumber) int
- func GetLengthOfNationalDestinationCode(number *PhoneNumber) int
- func GetNationalSignificantNumber(number *PhoneNumber) string
- func GetNddPrefixForRegion(regionCode string, stripNonDigits bool) string
- func GetRegionCodeForCountryCode(countryCallingCode int) string
- func GetRegionCodeForNumber(number *PhoneNumber) string
- func GetRegionCodesForCountryCode(countryCallingCode int) []string
- func GetSafeCarrierDisplayNameForNumber(phoneNumber *PhoneNumber, lang string) (string, error)
- func GetSupportedCallingCodes() map[int]bool
- func GetSupportedGlobalNetworkCallingCodes() map[int]bool
- func GetSupportedRegions() map[string]bool
- func GetSupportedTypesForNonGeoEntity(countryCallingCode int) map[PhoneNumberType]bool
- func GetSupportedTypesForRegion(regionCode string) map[PhoneNumberType]bool
- func GetTimeZonesForGeographicalNumber(number *PhoneNumber) ([]string, error)
- func GetTimeZonesForNumber(number *PhoneNumber) ([]string, error)
- func GetTimezonesForNumber(number *PhoneNumber) ([]string, error)
- func GetTimezonesForPrefix(number string) ([]string, error)
- func IsAlphaNumber(number string) bool
- func IsCarrierSpecific(number *PhoneNumber) bool
- func IsCarrierSpecificForRegion(number *PhoneNumber, regionDialingFrom string) bool
- func IsEmergencyNumber(number string, regionCode string) bool
- func IsMobileNumberPortableRegion(regionCode string) bool
- func IsNANPACountry(regionCode string) bool
- func IsNationalPrefixPresentIfRequired(number *PhoneNumber) bool
- func IsNumberGeographical(number *PhoneNumber) bool
- func IsNumberGeographicalForType(numberType PhoneNumberType, countryCallingCode int) bool
- func IsPossibleNumber(number *PhoneNumber) bool
- func IsPossibleNumberForType(number *PhoneNumber, numberType PhoneNumberType) bool
- func IsPossibleNumberFromRegion(number, regionDialingFrom string) bool
- func IsPossibleShortNumber(number *PhoneNumber) bool
- func IsPossibleShortNumberForRegion(number *PhoneNumber, regionDialingFrom string) bool
- func IsSmsServiceForRegion(number *PhoneNumber, regionDialingFrom string) bool
- func IsValidNumber(number *PhoneNumber) bool
- func IsValidNumberForRegion(number *PhoneNumber, regionCode string) bool
- func IsValidShortNumber(number *PhoneNumber) bool
- func IsValidShortNumberForRegion(number *PhoneNumber, regionDialingFrom string) bool
- func LoadNetworks() error
- func MatchNationalNumber(number string, numberDesc *PhoneNumberDesc, allowPrefixMatch bool) bool
- func MaybeSeparateExtensionFromPhone(rawPhone string) (phoneNumber string, extension string)
- func Name(code string) string
- func NormalizeDiallableCharsOnly(number string) string
- func NormalizeDigitsOnly(number string) string
- func ParseAndKeepRawInputToNumber(numberToParse, defaultRegion string, phoneNumber *PhoneNumber) error
- func ParseToNumber(numberToParse, defaultRegion string, phoneNumber *PhoneNumber) error
- func Phone(code string) string
- func TruncateTooLongNumber(number *PhoneNumber) bool
- func Worker(data map[string]string) bool
- type AnalyzeCarrierResult
- type AnalyzeCountryResult
- type AsYouTypeFormatter
- type CarrierStats
- type Country
- type CountryStats
- type Leniency
- type MatchType
- type Network
- type Number
- type NumberFormat
- func (*NumberFormat) Descriptor() ([]byte, []int)deprecated
- func (x *NumberFormat) GetDomesticCarrierCodeFormattingRule() string
- func (x *NumberFormat) GetFormat() string
- func (x *NumberFormat) GetLeadingDigitsPattern() []string
- func (x *NumberFormat) GetNationalPrefixFormattingRule() string
- func (x *NumberFormat) GetNationalPrefixOptionalWhenFormatting() bool
- func (x *NumberFormat) GetPattern() string
- func (*NumberFormat) ProtoMessage()
- func (x *NumberFormat) ProtoReflect() protoreflect.Message
- func (x *NumberFormat) Reset()
- func (x *NumberFormat) String() string
- type NumberFormatE
- type Numbers
- type Ops
- type PhoneMetadata
- func (*PhoneMetadata) Descriptor() ([]byte, []int)deprecated
- func (x *PhoneMetadata) GetCarrierSpecific() *PhoneNumberDesc
- func (x *PhoneMetadata) GetCountryCode() int32
- func (x *PhoneMetadata) GetEmergency() *PhoneNumberDesc
- func (x *PhoneMetadata) GetFixedLine() *PhoneNumberDesc
- func (x *PhoneMetadata) GetGeneralDesc() *PhoneNumberDesc
- func (x *PhoneMetadata) GetId() string
- func (x *PhoneMetadata) GetInternationalPrefix() string
- func (x *PhoneMetadata) GetIntlNumberFormat() []*NumberFormat
- func (x *PhoneMetadata) GetLeadingDigits() string
- func (x *PhoneMetadata) GetLeadingZeroPossible() bool
- func (x *PhoneMetadata) GetMainCountryForCode() bool
- func (x *PhoneMetadata) GetMobile() *PhoneNumberDesc
- func (x *PhoneMetadata) GetMobileNumberPortableRegion() bool
- func (x *PhoneMetadata) GetNationalPrefix() string
- func (x *PhoneMetadata) GetNationalPrefixForParsing() string
- func (x *PhoneMetadata) GetNationalPrefixTransformRule() string
- func (x *PhoneMetadata) GetNoInternationalDialling() *PhoneNumberDesc
- func (x *PhoneMetadata) GetNumberFormat() []*NumberFormat
- func (x *PhoneMetadata) GetPager() *PhoneNumberDesc
- func (x *PhoneMetadata) GetPersonalNumber() *PhoneNumberDesc
- func (x *PhoneMetadata) GetPreferredExtnPrefix() string
- func (x *PhoneMetadata) GetPreferredInternationalPrefix() string
- func (x *PhoneMetadata) GetPremiumRate() *PhoneNumberDesc
- func (x *PhoneMetadata) GetSameMobileAndFixedLinePattern() bool
- func (x *PhoneMetadata) GetSharedCost() *PhoneNumberDesc
- func (x *PhoneMetadata) GetShortCode() *PhoneNumberDesc
- func (x *PhoneMetadata) GetSmsServices() *PhoneNumberDesc
- func (x *PhoneMetadata) GetStandardRate() *PhoneNumberDesc
- func (x *PhoneMetadata) GetTollFree() *PhoneNumberDesc
- func (x *PhoneMetadata) GetUan() *PhoneNumberDesc
- func (x *PhoneMetadata) GetVoicemail() *PhoneNumberDesc
- func (x *PhoneMetadata) GetVoip() *PhoneNumberDesc
- func (*PhoneMetadata) ProtoMessage()
- func (x *PhoneMetadata) ProtoReflect() protoreflect.Message
- func (x *PhoneMetadata) Reset()
- func (x *PhoneMetadata) String() string
- type PhoneMetadataCollection
- func BuildAlternateFormatsMetadataCollection(inputXML []byte) (*PhoneMetadataCollection, error)
- func BuildPhoneMetadataCollection(inputXML []byte, liteBuild bool, specialBuild bool, isShortNumberMetadata bool) (*PhoneMetadataCollection, error)
- func MetadataCollection() (*PhoneMetadataCollection, error)
- func ShortNumberMetadataCollection() (*PhoneMetadataCollection, error)
- func (*PhoneMetadataCollection) Descriptor() ([]byte, []int)deprecated
- func (x *PhoneMetadataCollection) GetMetadata() []*PhoneMetadata
- func (*PhoneMetadataCollection) ProtoMessage()
- func (x *PhoneMetadataCollection) ProtoReflect() protoreflect.Message
- func (x *PhoneMetadataCollection) Reset()
- func (x *PhoneMetadataCollection) String() string
- type PhoneNumber
- func GetExampleNumber(regionCode string) *PhoneNumber
- func GetExampleNumberForNonGeoEntity(countryCallingCode int) *PhoneNumber
- func GetExampleNumberForType(regionCode string, typ PhoneNumberType) *PhoneNumber
- func GetInvalidExampleNumber(regionCode string) *PhoneNumber
- func Parse(numberToParse, defaultRegion string) (*PhoneNumber, error)
- func ParseAndKeepRawInput(numberToParse, defaultRegion string) (*PhoneNumber, error)
- func (*PhoneNumber) Descriptor() ([]byte, []int)deprecated
- func (x *PhoneNumber) GetCountryCode() int32
- func (x *PhoneNumber) GetCountryCodeSource() PhoneNumber_CountryCodeSource
- func (x *PhoneNumber) GetExtension() string
- func (x *PhoneNumber) GetItalianLeadingZero() bool
- func (x *PhoneNumber) GetNationalNumber() uint64
- func (x *PhoneNumber) GetNumberOfLeadingZeros() int32
- func (x *PhoneNumber) GetPreferredDomesticCarrierCode() string
- func (x *PhoneNumber) GetRawInput() string
- func (*PhoneNumber) ProtoMessage()
- func (x *PhoneNumber) ProtoReflect() protoreflect.Message
- func (x *PhoneNumber) Reset()
- func (x *PhoneNumber) String() string
- type PhoneNumberDesc
- func (*PhoneNumberDesc) Descriptor() ([]byte, []int)deprecated
- func (x *PhoneNumberDesc) GetExampleNumber() string
- func (x *PhoneNumberDesc) GetNationalNumberPattern() string
- func (x *PhoneNumberDesc) GetPossibleLength() []int32
- func (x *PhoneNumberDesc) GetPossibleLengthLocalOnly() []int32
- func (*PhoneNumberDesc) ProtoMessage()
- func (x *PhoneNumberDesc) ProtoReflect() protoreflect.Message
- func (x *PhoneNumberDesc) Reset()
- func (x *PhoneNumberDesc) String() string
- type PhoneNumberDescE
- type PhoneNumberFormat
- type PhoneNumberMatch
- type PhoneNumberMetadataE
- type PhoneNumberType
- type PhoneNumber_CountryCodeSource
- func (PhoneNumber_CountryCodeSource) Descriptor() protoreflect.EnumDescriptor
- func (x PhoneNumber_CountryCodeSource) Enum() *PhoneNumber_CountryCodeSource
- func (PhoneNumber_CountryCodeSource) EnumDescriptor() ([]byte, []int)deprecated
- func (x PhoneNumber_CountryCodeSource) Number() protoreflect.EnumNumber
- func (x PhoneNumber_CountryCodeSource) String() string
- func (PhoneNumber_CountryCodeSource) Type() protoreflect.EnumType
- func (x *PhoneNumber_CountryCodeSource) UnmarshalJSON(b []byte) errordeprecated
- type PossibleLengthE
- type Query
- type ShortNumberCost
- type StringBuilder
- func (b *StringBuilder) ByteAt(i int) (byte, error)
- func (b *StringBuilder) Bytes() []byte
- func (b *StringBuilder) Insert(i int, p []byte) (int, error)
- func (b *StringBuilder) InsertString(i int, s string) (int, error)
- func (b *StringBuilder) Len() int
- func (b *StringBuilder) Reset()
- func (b *StringBuilder) ResetWith(buf []byte) (int, error)
- func (b *StringBuilder) ResetWithString(s string) (int, error)
- func (b *StringBuilder) String() string
- func (b *StringBuilder) Write(p []byte) (int, error)
- func (b *StringBuilder) WriteByte(c byte) error
- func (b *StringBuilder) WriteRune(r rune) (int, error)
- func (b *StringBuilder) WriteString(s string) (int, error)
- type TerritoryE
- type UnverifiedNumbers
- type ValidationResult
- type VerifiedNumbers
Constants ¶
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.
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 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" )
const DIGIT_PLACEHOLDER = " "
DIGIT_PLACEHOLDER represents the digits that have not been entered yet, using , the punctuation space.
const (
Default_NumberFormat_NationalPrefixOptionalWhenFormatting = bool(false)
)
Default values for NumberFormat fields.
const (
Default_PhoneNumber_NumberOfLeadingZeros = int32(1)
)
Default values for PhoneNumber fields.
const MIN_LEADING_DIGITS_LENGTH = 3
MIN_LEADING_DIGITS_LENGTH is the minimum length of national number accrued that is required to trigger the formatter. The first element of the leadingDigitsPattern of each numberFormat contains a regular expression that matches up to this number of digits.
const MetadataVersion = "v9.0.33"
MetadataVersion is the upstream libphonenumber release tag that the embedded metadata under data/ was built from.
const SEPARATOR_BEFORE_NATIONAL_NUMBER = ' '
SEPARATOR_BEFORE_NATIONAL_NUMBER is the character used when appropriate to separate a prefix, such as a long NDD or a country calling code, from the national number.
Variables ¶
var ( // EMPTY_METADATA is used as a default instance of metadata. It allows the // formatter to function with an incorrect region code, even if formatting only // works for numbers specified with "+". EMPTY_METADATA = &PhoneMetadata{ Id: proto.String("<ignored>"), InternationalPrefix: proto.String("NA"), } // ELIGIBLE_FORMAT_PATTERN determines if a numberFormat under availableFormats is // eligible to be used by the formatter. It is eligible when the format element // under numberFormat contains groups of the dollar sign followed by a single // digit, separated by valid phone number punctuation. This prevents invalid // punctuation (such as the star sign in Israeli star numbers) getting into the // output of the formatter. We require that the first group is present in the // output pattern to ensure no data is lost while formatting; when we format as // you type, this should always be the case. Anchored to require a full match, // mirroring Java's Matcher.matches(). ELIGIBLE_FORMAT_PATTERN = regexp.MustCompile("^(?:[" + VALID_PUNCTUATION + "]*" + "\\$1" + "[" + VALID_PUNCTUATION + "]*(?:\\$\\d" + "[" + VALID_PUNCTUATION + "]*)*)$") // NATIONAL_PREFIX_SEPARATORS_PATTERN is a set of characters that, if found in a // national prefix formatting rule, are an indicator to us that we should // separate the national prefix from the number when formatting. NATIONAL_PREFIX_SEPARATORS_PATTERN = regexp.MustCompile("[- ]") )
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.
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{ 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{ '0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '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. // Anchored to require a full match, mirroring Java's Pattern.matches(): Go's // MatchString is a partial (unanchored) match, which would wrongly treat a // regex IDD prefix like "0[0-3][0-9]" as a unique prefix (matching its leading // "0") instead of falling back to international "+" formatting. 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. " // Regexp of all possible ways to write extensions, for use when // parsing. This will be run as a case-insensitive regexp match. // maybeStripExtension iterates over all submatches of this pattern // and assumes that every capturing group corresponds to the // extension digits. When modifying this regexp, ensure that any // non-extension grouping uses non-capturing groups (?:...) so as // not to introduce additional capturing groups that would break // extension parsing. // // The first regular expression covers RFC 3966 format, where the // extension is added using ";ext=". The second is a more generic // expression where the extension is mentioned with explicit labels like "ext:". In both // cases we allow more digits. The third captures when single // character extension labels or less commonly used labels are used, // with fewer extension digits to reduce false positives. The fourth // covers American numbers where the extension is written with a // hash at the end, such as "- 503#". EXTN_PATTERNS_FOR_MATCHING = RFC3966_EXTN_PREFIX + "(" + DIGITS + "{1,20})" + "|" + possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels + possibleCharsAfterExtLabel + "(" + DIGITS + "{1,20})" + optionalExtnSuffix + "|" + possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels + possibleCharsAfterExtLabel + "(" + DIGITS + "{1,9})" + optionalExtnSuffix + "|" + ambiguousSeparator + "(" + DIGITS + "{1,6})#" EXTN_PATTERNS_FOR_PARSING = EXTN_PATTERNS_FOR_MATCHING + "|" + possibleSeparatorsNumberExtLabelNoComma + autoDiallingAndExtLabelsFound + possibleCharsAfterExtLabel + "(" + DIGITS + "{1,15})" + optionalExtnSuffix + "|" + possibleSeparatorsNumberExtLabelNoComma + "(?:,)+" + possibleCharsAfterExtLabel + "(" + DIGITS + "{1,9})" + optionalExtnSuffix // 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("(?i)(?:" + 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( "(?i)^(" + 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) // Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES // below) which are not based on *area codes*. For example, in China mobile numbers start with a // carrier indicator, and beyond that are geographically assigned: this carrier indicator is not // considered to be an area code. GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES = map[int32]bool{ 86: true, } // Set of country codes that doesn't have national prefix, but it has area codes. COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES = map[int32]bool{ 52: true, } // Set of country calling codes that have geographically assigned mobile numbers. This may not be // complete; we add calling codes case by case, as we find geographical mobile numbers or hear // from user reports. Note that countries like the US, where we can't distinguish between // fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be // a possibly geographically-related type anyway (like FIXED_LINE). GEO_MOBILE_COUNTRIES = map[int32]bool{ 52: true, 54: true, 55: true, 62: true, 86: true, } )
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") )
var Countries = map[string]Country{}/* 245 elements not displayed */
Countries holds the raw data
var CountryNetwork = map[string][]Network{}
var ErrEmptyMetadata = errors.New("empty metadata")
var ErrInvalidIndex = errors.New("phonenumbers.StringBuilder: invalid index")
ErrInvalidIndex is returned by Insert/InsertString/ByteAt when the given index falls outside the buffer.
var ErrNumTooLong = errors.New("the string supplied is too long to be a phone number")
var ErrTooShortAfterIDD = errors.New("phone number had an IDD, but " +
"after this was not long enough to be a viable phone number")
var File_phonemetadata_proto protoreflect.FileDescriptor
var File_phonenumber_proto protoreflect.FileDescriptor
var REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT = []string{"BR", "CL", "NI"}
In these countries, if extra digits are added to an emergency number, it no longer connects to the emergency service.
var Type = map[int]string{
0: "FIXED_LINE",
1: "MOBILE",
2: "FIXED_LINE_OR_MOBILE",
3: "TOLL_FREE",
4: "PREMIUM_RATE",
5: "SHARED_COST",
6: "VOIP",
7: "PERSONAL_NUMBER",
8: "PAGER",
9: "UAN",
10: "UNKNOWN",
11: "UNKNOWN",
27: "EMERGENCY",
28: "VOICEMAIL",
29: "SHORT_CODE",
}
Functions ¶
func AllNumberGroupsAreExactlyPresent ¶
func AllNumberGroupsAreExactlyPresent( number *PhoneNumber, normalizedCandidate string, formattedNumberGroups []string) bool
AllNumberGroupsAreExactlyPresent reports that the groups of digits in the candidate exactly match how the number would be formatted (the EXACT_GROUPING check).
func AllNumberGroupsRemainGrouped ¶
func AllNumberGroupsRemainGrouped( number *PhoneNumber, normalizedCandidate string, formattedNumberGroups []string) bool
AllNumberGroupsRemainGrouped reports that the number groups found in the candidate are not broken up differently from how the number would be formatted (the STRICT_GROUPING check).
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 CanBeInternationallyDialled ¶
func CanBeInternationallyDialled(number *PhoneNumber) bool
CanBeInternationallyDialled reports whether number may be dialled from outside its region. It does not validate the number first.
func CheckNumberGroupingIsValid ¶
func CheckNumberGroupingIsValid( number *PhoneNumber, candidate string, checker func(number *PhoneNumber, normalizedCandidate string, expectedNumberGroups []string) bool) bool
CheckNumberGroupingIsValid checks the digit groups of candidate against the expected grouping for number using checker, falling back to any alternate formats for the number's country calling code.
func Clean ¶
func Clean(phone []string, defaultRegion ...string) (VerifiedNumbers, UnverifiedNumbers)
func ConnectsToEmergencyNumber ¶
Returns true if the given number, exactly as dialed, might be used to connect to an emergency service in the given region.
This method accepts a string, rather than a PhoneNumber, because it needs to distinguish cases such as "+1 911" and "911", where the former may not connect to an emergency service in all cases but the latter would. This method takes into account cases where the number might contain formatting, or might have additional digits appended (when it is okay to do that in the specified region).
number: the phone number to test regionCode: the region where the phone number is being dialed return: whether the number might be used to connect to an emergency service in the given region
func ContainsMoreThanOneSlashInNationalNumber ¶
func ContainsMoreThanOneSlashInNationalNumber(number *PhoneNumber, candidate string) bool
ContainsMoreThanOneSlashInNationalNumber reports whether candidate contains more than one slash in the national-number portion (used to reject dates).
func ContainsOnlyValidXChars ¶
func ContainsOnlyValidXChars(number *PhoneNumber, candidate string) bool
ContainsOnlyValidXChars reports whether every 'x'/'X' in candidate represents a carrier code or an extension sign (and not, say, a vanity-number letter).
func ConvertAlphaCharactersInNumber ¶
Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.
func CountryCodes ¶
func CountryCodes() []string
CountryCodes returns a list of country codes, sorted by alpha
func CountryNames ¶
func CountryNames() []string
CountryNames returns a list of country names, sorted by alpha
func Currency ¶
Currency returns a countries currency. Note that it defaults to an empty string if country not found
func CurrencySymbol ¶
CurrencySymbol returns a countries currency symbol. Note that it defaults to an empty string if country not found
func FindNumbers ¶
func FindNumbers(text, defaultRegion string) iter.Seq[*PhoneNumberMatch]
FindNumbers returns an iterator over all phone-number matches in text. It is a shortcut for FindNumbersWithLeniency with VALID leniency and no limit on the number of invalid candidates tried. defaultRegion is the region to assume for numbers not written in international format; pass "" or "ZZ" to only consider numbers with a leading plus.
Range over the result with for/range:
for m := range phonenumbers.FindNumbers(text, "US") {
fmt.Println(m.RawString(), m.Start(), m.End())
}
func FindNumbersWithLeniency ¶
func FindNumbersWithLeniency(text, defaultRegion string, leniency Leniency, maxTries int) iter.Seq[*PhoneNumberMatch]
FindNumbersWithLeniency returns an iterator over all phone-number matches in text at the given leniency. maxTries caps the number of invalid candidates tried before giving up, to bound degenerate inputs with many false positives (use math.MaxInt for no practical limit). Must be >= 0.
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
deprecated
func FormatWithBuf(number *PhoneNumber, numberFormat PhoneNumberFormat, formattedNumber *StringBuilder)
Same as Format(PhoneNumber, PhoneNumberFormat), but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times.
Deprecated: use Format instead. This only exists to mirror Java's format(PhoneNumber, PhoneNumberFormat, StringBuilder) overload, and it leaks the internal StringBuilder type into the public API. The allocation it saves is negligible in practice, since formatting must prepend the country calling code, which forces the buffer to be rebuilt on every call anyway.
func GetCarrierForNumber ¶
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 GetCarrierForValidNumber ¶
func GetCarrierForValidNumber(number *PhoneNumber, lang string) (string, error)
GetCarrierForValidNumber performs carrier lookup without repeating number type validation. Callers must supply a valid mobile-capable number.
func GetCarrierWithPrefixForNumber ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GetSupportedGlobalNetworkCallingCodes returns all global network calling codes the library has metadata for.
func GetSupportedRegions ¶
GetSupportedRegions returns all regions the library has metadata for.
func GetSupportedTypesForNonGeoEntity ¶
func GetSupportedTypesForNonGeoEntity(countryCallingCode int) map[PhoneNumberType]bool
GetSupportedTypesForNonGeoEntity returns the types for a country-code belonging to a non-geographical entity which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE or UNKNOWN. No types are returned for country calling codes that do not map to a known non-geographical entity.
func GetSupportedTypesForRegion ¶
func GetSupportedTypesForRegion(regionCode string) map[PhoneNumberType]bool
GetSupportedTypesForRegion returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE or UNKNOWN. No types are returned for invalid or unknown region codes.
func GetTimeZonesForGeographicalNumber ¶
func GetTimeZonesForGeographicalNumber(number *PhoneNumber) ([]string, error)
GetTimeZonesForGeographicalNumber returns time zones for a parsed geographical number.
func GetTimeZonesForNumber ¶
func GetTimeZonesForNumber(number *PhoneNumber) ([]string, error)
GetTimeZonesForNumber is the upstream-compatible spelling of GetTimezonesForNumber.
func GetTimezonesForNumber ¶
func GetTimezonesForNumber(number *PhoneNumber) ([]string, error)
GetTimezonesForNumber returns the names of timezones which we believe maps to the passed in number.
func GetTimezonesForPrefix ¶
GetTimezonesForPrefix returns a slice of Timezones corresponding to the number passed or error when it is impossible to convert the string to int The algorithm 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 ¶
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 IsCarrierSpecific ¶
func IsCarrierSpecific(number *PhoneNumber) bool
IsCarrierSpecific given a valid short number, determines whether it is carrier-specific (however, nothing is implied about its validity). Carrier-specific numbers may connect to a different end-point, or not connect at all, depending on the user's carrier. If it is important that the number is valid, then its validity must first be checked using IsValidShortNumber or IsValidShortNumberForRegion.
func IsCarrierSpecificForRegion ¶
func IsCarrierSpecificForRegion(number *PhoneNumber, regionDialingFrom string) bool
IsCarrierSpecificForRegion given a valid short number, determines whether it is carrier-specific when dialed from the given region (however, nothing is implied about its validity). Returns false if the number doesn't match the region provided.
func IsEmergencyNumber ¶
Returns true if the given number exactly matches an emergency service number in the given region.
This method takes into account cases where the number might contain formatting, but doesn't allow additional digits to be appended. Note that isEmergencyNumber(number, region) implies connectsToEmergencyNumber(number, region).
number: the phone number to test regionCode: the region where the phone number is being dialed return: whether the number exactly matches an emergency services number in the given region
func IsMobileNumberPortableRegion ¶
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 ¶
Checks if this is a region under the North American Numbering Plan Administration (NANPA).
func IsNationalPrefixPresentIfRequired ¶
func IsNationalPrefixPresentIfRequired(number *PhoneNumber) bool
IsNationalPrefixPresentIfRequired reports whether, if a national prefix is required to format number, it was present in the raw input.
func IsNumberGeographical ¶
func IsNumberGeographical(number *PhoneNumber) bool
IsNumberGeographical reports whether number has a geographical association.
func IsNumberGeographicalForType ¶
func IsNumberGeographicalForType(numberType PhoneNumberType, countryCallingCode int) bool
IsNumberGeographicalForType is the cheaper form of IsNumberGeographical when the caller already knows the number type and calling code.
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 IsPossibleNumberForType ¶
func IsPossibleNumberForType(number *PhoneNumber, numberType PhoneNumberType) bool
IsPossibleNumberForType returns true if the number is a possible number of the given type (a more lenient check than IsValidNumberForRegion).
func IsPossibleNumberFromRegion ¶
IsPossibleNumberFromRegion parses number as dialled from regionDialingFrom and reports whether its length is possible. It is intentionally more lenient than IsValidNumber.
func IsPossibleShortNumber ¶
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 ¶
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 IsSmsServiceForRegion ¶
func IsSmsServiceForRegion(number *PhoneNumber, regionDialingFrom string) bool
IsSmsServiceForRegion given a valid short number, determines whether it is an SMS service (however, nothing is implied about its validity). An SMS service is where the primary or only intended usage is to receive and/or send text messages (SMSs). This includes MMS as MMS numbers downgrade to SMS if the other party isn't MMS-capable. Returns false if the number doesn't match the region provided.
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 ¶
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 ¶
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 LoadNetworks ¶
func LoadNetworks() error
func MatchNationalNumber ¶
func MatchNationalNumber(number string, numberDesc *PhoneNumberDesc, allowPrefixMatch bool) bool
MatchNationalNumber reports whether the given national number (a string of decimal digits) matches the national number pattern in numberDesc.
func MaybeSeparateExtensionFromPhone ¶
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 Name ¶
Name returns a countries name. Note that it defaults to an empty string if country not found
func NormalizeDiallableCharsOnly ¶
NormalizeDiallableCharsOnly strips characters that cannot be dialled on a phone keypad, including non-ASCII digits.
func NormalizeDigitsOnly ¶
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 Phone ¶
Phone returns a countries phone ext. Note that it defaults to an empty string if country not found
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 AnalyzeCarrierResult ¶
type AnalyzeCountryResult ¶
type AsYouTypeFormatter ¶
type AsYouTypeFormatter struct {
// contains filtered or unexported fields
}
AsYouTypeFormatter formats phone numbers as they are entered. It is a port of libphonenumber's AsYouTypeFormatter (Java reference implementation).
An AsYouTypeFormatter is obtained from GetAsYouTypeFormatter. After that, digits can be added by calling InputDigit on the instance, and the partially formatted phone number is returned each time a digit is added. Clear can be called before formatting a new number.
See AsYouTypeFormatter's tests for more details on how the formatter is to be used.
func GetAsYouTypeFormatter ¶
func GetAsYouTypeFormatter(regionCode string) *AsYouTypeFormatter
GetAsYouTypeFormatter returns an AsYouTypeFormatter for the specific region.
func (*AsYouTypeFormatter) Clear ¶
func (aytf *AsYouTypeFormatter) Clear()
Clear clears the internal state of the formatter, so it can be reused.
func (*AsYouTypeFormatter) GetRememberedPosition ¶
func (aytf *AsYouTypeFormatter) GetRememberedPosition() int
GetRememberedPosition returns the current position in the partially formatted phone number of the character which was previously passed in as the parameter of InputDigitAndRememberPosition.
func (*AsYouTypeFormatter) InputDigit ¶
func (aytf *AsYouTypeFormatter) InputDigit(nextChar rune) string
InputDigit formats a phone number on-the-fly as each digit is entered.
nextChar is the most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered this method formats the number as entered and not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will be shown as they are. It returns the partially formatted phone number.
func (*AsYouTypeFormatter) InputDigitAndRememberPosition ¶
func (aytf *AsYouTypeFormatter) InputDigitAndRememberPosition(nextChar rune) string
InputDigitAndRememberPosition is the same as InputDigit, but remembers the position where nextChar is inserted, so that it can be retrieved later using GetRememberedPosition. The remembered position will be automatically adjusted if additional formatting characters are later inserted/removed in front of nextChar.
type CarrierStats ¶
type CarrierStats struct {
Result map[string]*AnalyzeCarrierResult `json:"-"`
RS []*AnalyzeCarrierResult `json:"result"`
InvalidCount int `json:"invalid_count"`
TotalCount int `json:"total_count"`
}
func StatsByCarrier ¶
func StatsByCarrier(phone []string, defaultRegion ...string) CarrierStats
type Country ¶
type Country struct {
Code string // AU
Currency string // AUD
CurrencySymbol string // $
Name string // Australia
Phone string // +61
}
Country holds the counties details
func GetCountry ¶
GetCountry returns a country based on the code
type CountryStats ¶
type CountryStats struct {
Result map[string]*AnalyzeCountryResult `json:"-"`
RS []*AnalyzeCountryResult `json:"result"`
InvalidCount int `json:"invalid_count"`
TotalCount int `json:"total_count"`
}
func StatsByCountry ¶
func StatsByCountry(phone []string, defaultRegion ...string) CountryStats
type MatchType ¶
type MatchType int
func IsNumberMatch ¶
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 ¶
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 ¶
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 Network ¶
type Network struct {
Plmn string `json:"plmn"`
NibbledPlmn string `json:"nibbledPlmn"`
Mcc string `json:"mcc"`
Mnc string `json:"mnc"`
Region string `json:"region"`
Type string `json:"type"`
CountryName string `json:"countryName"`
CountryCode string `json:"countryCode"`
Lat string `json:"lat"`
Long string `json:"long"`
Brand string `json:"brand"`
Operator string `json:"operator"`
Status string `json:"status"`
Bands string `json:"bands"`
Notes interface{} `json:"notes"`
}
type Number ¶
type Number struct {
Phone string `query:"phone" json:"phone" csv:"phone"`
DefaultPrefix string `query:"default_prefix" json:"default_prefix,omitempty" csv:"default_prefix,omitempty"`
PhoneTypeHuman string `json:"phone_type_human,omitempty" csv:"phone_type_human,omitempty"`
CarrierName string `json:"carrier_name,omitempty" csv:"carrier_name,omitempty"`
CarrierMcc string `json:"carrier_mcc,omitempty" csv:"carrier_mcc,omitempty"`
CarrierMnc string `json:"carrier_mnc,omitempty" csv:"carrier_mnc,omitempty"`
CarrierNnc string `json:"carrier_nnc,omitempty" csv:"carrier_nnc,omitempty"`
CountryName string `json:"country_name,omitempty" csv:"country_name,omitempty"`
CountryCode string `json:"country_code,omitempty" csv:"country_code,omitempty"`
Currency string `json:"currency,omitempty" csv:"currency,omitempty"`
CurrencySymbol string `json:"currency_symbol,omitempty" csv:"currency_symbol,omitempty"`
Timezone string `json:"timezone,omitempty" csv:"timezone,omitempty"`
Invalid bool `json:"invalid,omitempty" csv:"invalid,omitempty"`
DialCode int32 `json:"dial_code,omitempty" csv:"dial_code,omitempty"`
PhoneType int `json:"phone_type,omitempty" csv:"phone_type,omitempty"`
}
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 ¶
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 Numbers ¶
type Numbers struct {
Phones []string `json:"phones"`
DefaultPrefix string `query:"default_prefix" json:"default_prefix,omitempty"`
PhoneTypes []string `json:"phone_types"`
PhoneOnly bool `json:"phone_only"`
}
func (*Numbers) Clean ¶
func (p *Numbers) Clean() (VerifiedNumbers, UnverifiedNumbers)
func (*Numbers) StatsByCarrier ¶
func (p *Numbers) StatsByCarrier() CarrierStats
func (*Numbers) StatsByCountry ¶
func (p *Numbers) StatsByCountry() CountryStats
func (*Numbers) Verify ¶
func (p *Numbers) Verify() VerifiedNumbers
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"`
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 ¶
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 ¶
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 BuildAlternateFormatsMetadataCollection ¶
func BuildAlternateFormatsMetadataCollection(inputXML []byte) (*PhoneMetadataCollection, error)
BuildAlternateFormatsMetadataCollection compiles PhoneNumberAlternateFormats.xml. The alternate formats provide additional formatting patterns keyed by country calling code (the territory elements carry no region id), used by PhoneNumberMatcher's grouping leniency checks. No PhoneNumberDesc patterns are processed for this metadata.
func MetadataCollection ¶
func MetadataCollection() (*PhoneMetadataCollection, error)
MetadataCollection returns the embedded territory metadata collection. The result is parsed once and cached; it always reflects the embedded data and is independent of any container swapped in via useMetadata.
func ShortNumberMetadataCollection ¶
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 ¶
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 GetInvalidExampleNumber ¶
func GetInvalidExampleNumber(regionCode string) *PhoneNumber
GetInvalidExampleNumber returns an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what happens with an invalid number. Returns nil when an unsupported region or the region 001 (Earth) is passed in.
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 ¶
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 ¶
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 PhoneNumberMatch ¶
type PhoneNumberMatch struct {
// contains filtered or unexported fields
}
PhoneNumberMatch is the immutable match of a phone number within a piece of text. Matches may be found using FindNumbers.
A match consists of the phone number (Number) as well as the start and end byte offsets of the corresponding substring of the searched text. Use RawString to obtain the matched substring. Note that, unlike upstream's Java (which uses UTF-16 char offsets), Start and End are byte offsets into the searched string, so text[match.Start():match.End()] == match.RawString().
func (*PhoneNumberMatch) End ¶
func (m *PhoneNumberMatch) End() int
End returns the exclusive end byte offset of the matched phone number within the searched text.
func (*PhoneNumberMatch) Number ¶
func (m *PhoneNumberMatch) Number() *PhoneNumber
Number returns the phone number matched by the receiver.
func (*PhoneNumberMatch) RawString ¶
func (m *PhoneNumberMatch) RawString() string
RawString returns the raw substring matched as a phone number in the searched text.
func (*PhoneNumberMatch) Start ¶
func (m *PhoneNumberMatch) Start() int
Start returns the start byte offset of the matched phone number within the searched text.
func (*PhoneNumberMatch) String ¶
func (m *PhoneNumberMatch) String() string
String returns a human-readable representation of the match.
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 ¶
func (PhoneNumber_CountryCodeSource) Descriptor() protoreflect.EnumDescriptor
func (PhoneNumber_CountryCodeSource) Enum ¶
func (x PhoneNumber_CountryCodeSource) Enum() *PhoneNumber_CountryCodeSource
func (PhoneNumber_CountryCodeSource) EnumDescriptor
deprecated
func (PhoneNumber_CountryCodeSource) EnumDescriptor() ([]byte, []int)
Deprecated: Use PhoneNumber_CountryCodeSource.Descriptor instead.
func (PhoneNumber_CountryCodeSource) Number ¶
func (x PhoneNumber_CountryCodeSource) Number() protoreflect.EnumNumber
func (PhoneNumber_CountryCodeSource) String ¶
func (x PhoneNumber_CountryCodeSource) String() string
func (PhoneNumber_CountryCodeSource) Type ¶
func (PhoneNumber_CountryCodeSource) Type() protoreflect.EnumType
func (*PhoneNumber_CountryCodeSource) UnmarshalJSON
deprecated
func (x *PhoneNumber_CountryCodeSource) UnmarshalJSON(b []byte) error
Deprecated: Do not use.
type PossibleLengthE ¶
type ShortNumberCost ¶
type ShortNumberCost int
ShortNumberCost is the cost category of a short number.
const ( TOLL_FREE_COST ShortNumberCost = iota STANDARD_RATE_COST PREMIUM_RATE_COST UNKNOWN_COST )
Cost categories of short numbers. Note these are suffixed with _COST to avoid clashing with the PhoneNumberType constants TOLL_FREE and PREMIUM_RATE.
func GetExpectedCost ¶
func GetExpectedCost(number *PhoneNumber) ShortNumberCost
GetExpectedCost gets the expected cost category of a short number (however, nothing is implied about its validity). If the country calling code is unique to a region, this method behaves exactly the same as GetExpectedCostForRegion. However, if the country calling code is shared by multiple regions, then it returns the highest cost in the sequence PREMIUM_RATE, UNKNOWN_COST, STANDARD_RATE, TOLL_FREE. The reason for the position of UNKNOWN_COST in this order is that if a number is UNKNOWN_COST in one region but STANDARD_RATE or TOLL_FREE in another, its expected cost cannot be estimated as one of the latter since it might be a PREMIUM_RATE number.
Note: If the region from which the number is dialed is known, it is highly preferable to call GetExpectedCostForRegion instead.
func GetExpectedCostForRegion ¶
func GetExpectedCostForRegion(number *PhoneNumber, regionDialingFrom string) ShortNumberCost
GetExpectedCostForRegion gets the expected cost category of a short number when dialed from a region (however, nothing is implied about its validity). If it is important that the number is valid, then its validity must first be checked using IsValidShortNumberForRegion. Note that emergency numbers are always considered toll-free. Returns UNKNOWN_COST if the number does not match a cost category. Note that an invalid number may match any cost category.
func (ShortNumberCost) String ¶
func (c ShortNumberCost) String() string
type StringBuilder ¶
type StringBuilder struct {
// contains filtered or unexported fields
}
StringBuilder is a minimal, mutable string buffer that mirrors the parts of java.lang.StringBuilder the libphonenumber port relies on — chiefly the ability to insert at an arbitrary index, which neither strings.Builder nor bytes.Buffer provide. It is backed by a plain []byte and leans on the standard library (slices.Insert, utf8.AppendRune) for the heavy lifting.
func NewStringBuilder ¶
func NewStringBuilder(buf []byte) *StringBuilder
NewStringBuilder creates a StringBuilder using buf as its initial contents.
func NewStringBuilderString ¶
func NewStringBuilderString(s string) *StringBuilder
NewStringBuilderString creates a StringBuilder using s as its initial contents.
func (*StringBuilder) ByteAt ¶
func (b *StringBuilder) ByteAt(i int) (byte, error)
ByteAt returns the byte at index i, or ErrInvalidIndex if i is out of range.
func (*StringBuilder) Bytes ¶
func (b *StringBuilder) Bytes() []byte
Bytes returns the underlying contents. The slice is valid until the next mutating call; callers that retain it should copy.
func (*StringBuilder) Insert ¶
func (b *StringBuilder) Insert(i int, p []byte) (int, error)
Insert inserts p at index i, growing the buffer as needed. It returns ErrInvalidIndex if i is negative or greater than the buffer length.
func (*StringBuilder) InsertString ¶
func (b *StringBuilder) InsertString(i int, s string) (int, error)
InsertString inserts s at index i, growing the buffer as needed. It returns ErrInvalidIndex if i is negative or greater than the buffer length.
func (*StringBuilder) Len ¶
func (b *StringBuilder) Len() int
Len returns the number of bytes in the buffer.
func (*StringBuilder) Reset ¶
func (b *StringBuilder) Reset()
Reset empties the buffer while retaining its capacity.
func (*StringBuilder) ResetWith ¶
func (b *StringBuilder) ResetWith(buf []byte) (int, error)
ResetWith replaces the buffer's contents with buf.
func (*StringBuilder) ResetWithString ¶
func (b *StringBuilder) ResetWithString(s string) (int, error)
ResetWithString replaces the buffer's contents with s.
func (*StringBuilder) String ¶
func (b *StringBuilder) String() string
String returns the contents as a string. A nil receiver returns "<nil>", which is handy when debugging.
func (*StringBuilder) Write ¶
func (b *StringBuilder) Write(p []byte) (int, error)
Write appends p to the buffer. The error is always nil; it exists to satisfy io.Writer.
func (*StringBuilder) WriteByte ¶
func (b *StringBuilder) WriteByte(c byte) error
WriteByte appends c to the buffer. The error is always nil; it exists to satisfy io.ByteWriter.
func (*StringBuilder) WriteRune ¶
func (b *StringBuilder) WriteRune(r rune) (int, error)
WriteRune appends the UTF-8 encoding of r to the buffer and returns the number of bytes written. The error is always nil.
func (*StringBuilder) WriteString ¶
func (b *StringBuilder) WriteString(s string) (int, error)
WriteString appends s to the buffer. The error is always nil.
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,attr"`
// <!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:"noInternationalDialling"`
// <!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"`
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 smsServices (nationalNumberPattern, possibleLengths, exampleNumber)>
SmsServices *PhoneNumberDescE `xml:"smsServices"`
}
<!ELEMENT territory (references?, availableFormats?, generalDesc, noInternationalDialling?, fixedLine?, mobile?, pager?, tollFree?, premiumRate?, sharedCost?, personalNumber?, voip?, uan?, voicemail?)>
type UnverifiedNumbers ¶
type UnverifiedNumbers struct {
Phones []string `json:"phones"`
}
type ValidationResult ¶
type ValidationResult int
const ( IS_POSSIBLE ValidationResult = iota INVALID_COUNTRY_CODE TOO_SHORT TOO_LONG IS_POSSIBLE_LOCAL_ONLY INVALID_LENGTH )
func IsPossibleNumberForTypeWithReason ¶
func IsPossibleNumberForTypeWithReason(number *PhoneNumber, numberType PhoneNumberType) ValidationResult
IsPossibleNumberForTypeWithReason checks whether a phone number is a possible number of a particular type. For most number types, this is the same result as IsPossibleNumberWithReason. See that method for details.
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.
type VerifiedNumbers ¶
type VerifiedNumbers struct {
Phones []Number `json:"phones"`
DefaultPrefix string `query:"default_prefix" json:"default_prefix,omitempty"`
PhoneTypes []string `json:"phone_types"`
}
func VerifyList ¶
func VerifyList(phone []string, defaultRegion ...string) VerifiedNumbers
Source Files
¶
- alternateformats.go
- asyoutypeformatter.go
- builder.go
- carrier.go
- compatibility_api.go
- countries.go
- doc.go
- enums.go
- errors.go
- geocoding.go
- metadata.go
- metadata_util.go
- metadatasource.go
- metadataversion.go
- network.go
- networks.go
- phone.go
- phonemetadata.pb.go
- phonenumber.pb.go
- phonenumbermatch.go
- phonenumbermatcher.go
- phonenumberutil.go
- prefixmapper.go
- serialize.go
- shortnumberinfo.go
- stringbuilder.go
- timezone.go