Class PhoneNumberUtil
If you use this library, and want to be notified about important changes, please sign up to our mailing list. NOTE: A lot of methods in this class require Region Code strings. These must be provided using CLDR two-letter region-code format. These should be in upper-case. The list of the codes can be found here: http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic enum
Leniency when finding potential phone numbers in text segments.static enum
Types of phone number matches.static enum
INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation E.123.static enum
Type of phone numbers.static enum
Possible outcomes when testing if a PhoneNumber is possible. -
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionboolean
Returns true if the number can be dialled from outside the region, or unknown.static String
Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.static PhoneNumberUtil
createInstance
(MetadataLoader metadataLoader) Create a newPhoneNumberUtil
instance to carry out international phone number formatting, parsing, or validation.findNumbers
(CharSequence text, String defaultRegion) Returns an iterable over allPhoneNumberMatches
intext
.findNumbers
(CharSequence text, String defaultRegion, PhoneNumberUtil.Leniency leniency, long maxTries) Returns an iterable over allPhoneNumberMatches
intext
.format
(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat) Formats a phone number in the specified format using default rules.void
format
(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, StringBuilder formattedNumber) Same asformat(PhoneNumber, PhoneNumberFormat)
, but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times.formatByPattern
(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, List<Phonemetadata.NumberFormat> userDefinedFormats) Formats a phone number in the specified format using client-defined formatting rules.formatInOriginalFormat
(Phonenumber.PhoneNumber number, String regionCallingFrom) Formats a phone number using the original phone number format (e.g.formatNationalNumberWithCarrierCode
(Phonenumber.PhoneNumber number, CharSequence carrierCode) Formats a phone number in national format for dialing using the carrier as specified in thecarrierCode
.formatNationalNumberWithPreferredCarrierCode
(Phonenumber.PhoneNumber number, CharSequence fallbackCarrierCode) Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in.formatNumberForMobileDialing
(Phonenumber.PhoneNumber number, String regionCallingFrom, boolean withFormatting) Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region.formatOutOfCountryCallingNumber
(Phonenumber.PhoneNumber number, String regionCallingFrom) Formats a phone number for out-of-country dialing purposes.formatOutOfCountryKeepingAlphaChars
(Phonenumber.PhoneNumber number, String regionCallingFrom) Formats a phone number for out-of-country dialing purposes.getAsYouTypeFormatter
(String regionCode) Gets anAsYouTypeFormatter
for the specific region.int
getCountryCodeForRegion
(String regionCode) Returns the country calling code for a specific region.static String
getCountryMobileToken
(int countryCallingCode) Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string.getExampleNumber
(String regionCode) Gets a valid number for the specified region.getExampleNumberForNonGeoEntity
(int countryCallingCode) Gets a valid number for the specified country calling code for a non-geographical entity.Gets a valid number for the specified number type (it may belong to any country).getExampleNumberForType
(String regionCode, PhoneNumberUtil.PhoneNumberType type) Gets a valid number for the specified region and number type.static PhoneNumberUtil
Gets aPhoneNumberUtil
instance to carry out international phone number formatting, parsing, or validation.getInvalidExampleNumber
(String regionCode) Gets an invalid number for the specified region.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.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.Gets the national significant number of a phone number.getNddPrefixForRegion
(String regionCode, boolean stripNonDigits) Returns the national dialling prefix for a specific region.getNumberType
(Phonenumber.PhoneNumber number) Gets the type of a valid phone number.getRegionCodeForCountryCode
(int countryCallingCode) Returns the region code that matches the specific country calling code.Returns the region where a phone number is from.getRegionCodesForCountryCode
(int countryCallingCode) Returns a list with the region codes that match the specific country calling code.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.Returns all global network calling codes the library has metadata for.Returns all regions the library has metadata for.getSupportedTypesForNonGeoEntity
(int countryCallingCode) Returns the types for a country-code belonging to a non-geographical entity which the library has metadata for.getSupportedTypesForRegion
(String regionCode) Returns the types for a given region which the library has metadata for.boolean
isAlphaNumber
(CharSequence number) Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT.boolean
isMobileNumberPortableRegion
(String regionCode) Returns true if the supplied region supports mobile number portability.boolean
isNANPACountry
(String regionCode) Checks if this is a region under the North American Numbering Plan Administration (NANPA).boolean
isNumberGeographical
(Phonenumber.PhoneNumber phoneNumber) Tests whether a phone number has a geographical association.boolean
isNumberGeographical
(PhoneNumberUtil.PhoneNumberType phoneNumberType, int countryCallingCode) Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type is expensive; if we have already done this, we don't want to do it again.isNumberMatch
(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn) Takes two phone numbers and compares them for equality.isNumberMatch
(Phonenumber.PhoneNumber firstNumber, CharSequence secondNumber) Takes two phone numbers and compares them for equality.isNumberMatch
(CharSequence firstNumber, CharSequence secondNumber) Takes two phone numbers as strings and compares them for equality.boolean
Convenience wrapper aroundisPossibleNumberWithReason(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
.boolean
isPossibleNumber
(CharSequence number, String regionDialingFrom) Check whether a phone number is a possible number given a number in the form of a string, and the region where the number could be dialed from.boolean
isPossibleNumberForTypeWithReason
(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type) Check whether a phone number is a possible number of a particular type.Check whether a phone number is a possible number.boolean
isValidNumber
(Phonenumber.PhoneNumber number) Tests whether a phone number matches a valid pattern.boolean
isValidNumberForRegion
(Phonenumber.PhoneNumber number, String regionCode) Tests whether a phone number is valid for a certain region.static String
Normalizes a string of characters representing a phone number.static String
normalizeDigitsOnly
(CharSequence number) Normalizes a string of characters representing a phone number.parse
(CharSequence numberToParse, String defaultRegion) Parses a string and returns it as a phone number in proto buffer format.void
parse
(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber) Same asparse(CharSequence, String)
, but accepts mutable PhoneNumber as a parameter to decrease object creation when invoked many times.parseAndKeepRawInput
(CharSequence numberToParse, String defaultRegion) Parses a string and returns it in proto buffer format.void
parseAndKeepRawInput
(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber) Same asparseAndKeepRawInput(CharSequence, String)
, but accepts a mutable PhoneNumber as a parameter to decrease object creation when invoked many times.boolean
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.
-
Field Details
-
REGION_CODE_FOR_NON_GEO_ENTITY
- See Also:
-
-
Method Details
-
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.- Parameters:
number
- a string of characters representing a phone number- Returns:
- the normalized string version of the phone number
-
normalizeDiallableCharsOnly
Normalizes a string of characters representing a phone number. This strips all characters which are not diallable on a mobile phone keypad (including all non-ASCII digits).- Parameters:
number
- a string of characters representing a phone number- Returns:
- the normalized string version of the phone number
-
convertAlphaCharactersInNumber
Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting. -
getLengthOfGeographicalAreaCode
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:
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 generalPhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); PhoneNumber number = phoneUtil.parse("16502530000", "US"); String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number); String areaCode; String subscriberNumber; int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number); if (areaCodeLength > 0) { areaCode = nationalSignificantNumber.substring(0, areaCodeLength); subscriberNumber = nationalSignificantNumber.substring(areaCodeLength); } else { areaCode = ""; subscriberNumber = nationalSignificantNumber; }
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.
- Parameters:
number
- the PhoneNumber object for which clients want to know the length of the area code- Returns:
- the length of area code of the PhoneNumber object passed in
-
getLengthOfNationalDestinationCode
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. N.B.: similar to an area code, not all numbers have an NDC! An example of how this could be used:
Refer to the unittests to see the difference between this function andPhoneNumberUtil 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; }
getLengthOfGeographicalAreaCode(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
.- Parameters:
number
- the PhoneNumber object for which clients want to know the length of the NDC- Returns:
- the length of NDC of the PhoneNumber object passed in, which could be zero
-
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.- Parameters:
countryCallingCode
- the country calling code for which we want the mobile token- Returns:
- the mobile token, as a string, for the given country calling code
-
getSupportedRegions
Returns all regions the library has metadata for.- Returns:
- an unordered set of the two-letter region codes for every geographical region the library supports
-
getSupportedGlobalNetworkCallingCodes
Returns all global network calling codes the library has metadata for.- Returns:
- an unordered set of the country calling codes for every non-geographical entity the library supports
-
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.- Returns:
- an unordered set of the country calling codes for every geographical and non-geographical entity the library supports
-
getSupportedTypesForRegion
Returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN. No types will be returned for invalid or unknown region codes. -
getSupportedTypesForNonGeoEntity
public Set<PhoneNumberUtil.PhoneNumberType> getSupportedTypesForNonGeoEntity(int countryCallingCode) 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 (if numbers for this non-geographical entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN. No types will be returned for country calling codes that do not map to a known non-geographical entity. -
getInstance
Gets aPhoneNumberUtil
instance to carry out international phone number formatting, parsing, or validation. The instance is loaded with all phone number metadata.The
PhoneNumberUtil
is implemented as a singleton. Therefore, calling getInstance multiple times will only result in one instance being created.- Returns:
- a PhoneNumberUtil instance
-
createInstance
Create a newPhoneNumberUtil
instance to carry out international phone number formatting, parsing, or validation. The instance is loaded with all metadata by using the metadataLoader specified.This method should only be used in the rare case in which you want to manage your own metadata loading. Calling this method multiple times is very expensive, as each time a new instance is created from scratch. When in doubt, use
getInstance()
.- Parameters:
metadataLoader
- customized metadata loader. This should not be null- Returns:
- a PhoneNumberUtil instance
-
isNumberGeographical
Tests whether a phone number has a geographical association. It checks if the number is associated with a certain region in the country to which it belongs. Note that this doesn't verify if the number is actually in use. -
isNumberGeographical
public boolean isNumberGeographical(PhoneNumberUtil.PhoneNumberType phoneNumberType, int countryCallingCode) Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type is expensive; if we have already done this, we don't want to do it again. -
format
public String format(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat) 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.- Parameters:
number
- the phone number to be formattednumberFormat
- the format the phone number should be formatted into- Returns:
- the formatted phone number
-
format
public void format(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, StringBuilder formattedNumber) Same asformat(PhoneNumber, PhoneNumberFormat)
, but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times. -
formatByPattern
public String formatByPattern(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, List<Phonemetadata.NumberFormat> userDefinedFormats) 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.- Parameters:
number
- the phone number to be formattednumberFormat
- the format the phone number should be formatted intouserDefinedFormats
- formatting rules specified by clients- Returns:
- the formatted phone number
-
formatNationalNumberWithCarrierCode
public String formatNationalNumberWithCarrierCode(Phonenumber.PhoneNumber number, CharSequence carrierCode) Formats a phone number in national format for dialing using the carrier as specified in thecarrierCode
. ThecarrierCode
will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. IfcarrierCode
contains an empty string, returns the number in national format without any carrier code.- Parameters:
number
- the phone number to be formattedcarrierCode
- the carrier selection code to be used- Returns:
- the formatted phone number in national format for dialing using the carrier as
specified in the
carrierCode
-
formatNationalNumberWithPreferredCarrierCode
public String formatNationalNumberWithPreferredCarrierCode(Phonenumber.PhoneNumber number, CharSequence fallbackCarrierCode) 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 thefallbackCarrierCode
passed in instead. If there is nopreferredDomesticCarrierCode
, and thefallbackCarrierCode
contains an empty string, return the number in national format without any carrier code.Use
formatNationalNumberWithCarrierCode(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber, java.lang.CharSequence)
instead if the carrier code passed in should take precedence over the number'spreferredDomesticCarrierCode
when formatting.- Parameters:
number
- the phone number to be formattedfallbackCarrierCode
- the carrier selection code to be used, if none is found in the phone number itself- Returns:
- the formatted phone number in national format for dialing using the number's
preferredDomesticCarrierCode
, or thefallbackCarrierCode
passed in if none is found
-
formatNumberForMobileDialing
public String formatNumberForMobileDialing(Phonenumber.PhoneNumber number, String regionCallingFrom, boolean withFormatting) 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.- Parameters:
number
- the phone number to be formattedregionCallingFrom
- the region where the call is being placedwithFormatting
- whether the number should be returned with formatting symbols, such as spaces and dashes.- Returns:
- the formatted phone number
-
formatOutOfCountryCallingNumber
public String formatOutOfCountryCallingNumber(Phonenumber.PhoneNumber number, String regionCallingFrom) 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.
- Parameters:
number
- the phone number to be formattedregionCallingFrom
- the region where the call is being placed- Returns:
- the formatted phone number
-
formatInOriginalFormat
Formats a phone number using the original phone number format (e.g. INTERNATIONAL or NATIONAL) that the number is parsed from, provided that the number has been parsed withparseAndKeepRawInput(java.lang.CharSequence,java.lang.String)
. Otherwise the number will be formatted in NATIONAL format.The original format is embedded in the country_code_source field of the PhoneNumber object passed in, which is only set when parsing keeps the raw input. When we don't have a formatting pattern for the number, the method falls back to returning the raw input.
Note this method guarantees no digit will be inserted, removed or modified as a result of formatting.
- Parameters:
number
- the phone number that needs to be formatted in its original number formatregionCallingFrom
- the region whose IDD needs to be prefixed if the original number has one- Returns:
- the formatted phone number in its original number format
-
formatOutOfCountryKeepingAlphaChars
public String formatOutOfCountryKeepingAlphaChars(Phonenumber.PhoneNumber number, String regionCallingFrom) 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.
- Parameters:
number
- the phone number that needs to be formattedregionCallingFrom
- the region where the call is being placed- Returns:
- the formatted phone number
-
getNationalSignificantNumber
Gets the national significant number of a phone number. Note a national significant number doesn't contain a national prefix or any formatting.- Parameters:
number
- the phone number for which the national significant number is needed- Returns:
- the national significant number of the PhoneNumber object passed in
-
getExampleNumber
Gets a valid number for the specified region.- Parameters:
regionCode
- the region for which an example number is needed- Returns:
- a valid fixed-line number for the specified region. Returns null when the metadata
does not contain such information, or the region 001 is passed in. For 001 (representing
non-geographical numbers), call
getExampleNumberForNonGeoEntity(int)
instead.
-
getInvalidExampleNumber
Gets an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid *short* number/code for this region. Validity checking such numbers is handled withShortNumberInfo
.- Parameters:
regionCode
- the region for which an example number is needed- Returns:
- an invalid number for the specified region. Returns null when an unsupported region or the region 001 (Earth) is passed in.
-
getExampleNumberForType
public Phonenumber.PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberUtil.PhoneNumberType type) Gets a valid number for the specified region and number type.- Parameters:
regionCode
- the region for which an example number is neededtype
- the type of number that is needed- Returns:
- a valid number for the specified region and type. Returns null when the metadata
does not contain such information or if an invalid region or region 001 was entered.
For 001 (representing non-geographical numbers), call
getExampleNumberForNonGeoEntity(int)
instead.
-
getExampleNumberForType
Gets a valid number for the specified number type (it may belong to any country).- Parameters:
type
- the type of number that is needed- Returns:
- a valid number for the specified type. Returns null when the metadata does not contain such information. This should only happen when no numbers of this type are allocated anywhere in the world anymore.
-
getExampleNumberForNonGeoEntity
Gets a valid number for the specified country calling code for a non-geographical entity.- Parameters:
countryCallingCode
- the country calling code for a non-geographical entity- Returns:
- a valid number for the non-geographical entity. Returns null when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.
-
getNumberType
Gets the type of a valid phone number.- Parameters:
number
- the phone number that we want to know the type- Returns:
- the type of the phone number, or UNKNOWN if it is invalid
-
isValidNumber
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. It only verifies whether the parsed, canonicalised number is valid: not whether a particular series of digits entered by the user is diallable from the region provided when parsing. For example, the number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national significant number "789272696". This is valid, while the original string is not diallable.- Parameters:
number
- the phone number that we want to validate- Returns:
- a boolean that indicates whether the number is of a valid pattern
-
isValidNumberForRegion
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 useisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
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.- Parameters:
number
- the phone number that we want to validateregionCode
- the region that we want to validate the phone number for- Returns:
- a boolean that indicates whether the number is of a valid pattern
-
getRegionCodeForNumber
Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers).- Parameters:
number
- the phone number whose origin we want to know- Returns:
- the region where the phone number is from, or null if no region matches this calling code
-
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). -
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. -
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.- Parameters:
regionCode
- the region that we want to get the country calling code for- Returns:
- the country calling code for the region denoted by regionCode
-
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.
- Parameters:
regionCode
- the region that we want to get the dialling prefix forstripNonDigits
- true to strip non-digits from the national dialling prefix- Returns:
- the dialling prefix for the region denoted by regionCode
-
isNANPACountry
Checks if this is a region under the North American Numbering Plan Administration (NANPA).- Returns:
- true if regionCode is one of the regions under NANPA
-
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 asisPossibleNumberWithReason(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
andisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
should be used.- Parameters:
number
- the number that needs to be checked- Returns:
- true if the number is a valid vanity number
-
isPossibleNumber
Convenience wrapper aroundisPossibleNumberWithReason(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.- Parameters:
number
- the number that needs to be checked- Returns:
- true if the number is possible
-
isPossibleNumberForType
public boolean isPossibleNumberForType(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type) Convenience wrapper aroundisPossibleNumberForTypeWithReason(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber, com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType)
. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.- Parameters:
number
- the number that needs to be checkedtype
- the type we are interested in- Returns:
- true if the number is possible for this particular type
-
isPossibleNumberWithReason
Check whether a phone number is a possible number. It provides a more lenient check thanisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
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 some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY 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.
- Parameters:
number
- the number that needs to be checked- Returns:
- a ValidationResult object which indicates whether the number is possible
-
isPossibleNumberForTypeWithReason
public PhoneNumberUtil.ValidationResult isPossibleNumberForTypeWithReason(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type) Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you usegetSupportedTypesForRegion(java.lang.String)
orgetSupportedTypesForNonGeoEntity(int)
respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check thanisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
in the following sense:- It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
- For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY 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.
- Parameters:
number
- the number that needs to be checkedtype
- the type we are interested in- Returns:
- a ValidationResult object which indicates whether the number is possible
-
isPossibleNumber
Check whether a phone number is a possible number given a number in the form of a string, and the region where the number could be dialed from. It provides a more lenient check thanisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
. SeeisPossibleNumber(PhoneNumber)
for details.This method first parses the number, then invokes
isPossibleNumber(PhoneNumber)
with the resultant PhoneNumber object.- Parameters:
number
- the number that needs to be checkedregionDialingFrom
- the region that we are expecting the number to be dialed from. Note this is different from the region where the number belongs. For example, the number +1 650 253 0000 is a number that belongs to US. When written in this form, it can be dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any region which uses an international dialling prefix of 00. When it is written as 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it can only be dialed from within a smaller area in the US (Mountain View, CA, to be more specific).- Returns:
- true if the number is possible
-
truncateTooLongNumber
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.- Parameters:
number
- a PhoneNumber object which contains a number that is too long to be valid- Returns:
- true if a valid phone number can be successfully extracted
-
getAsYouTypeFormatter
Gets anAsYouTypeFormatter
for the specific region.- Parameters:
regionCode
- the region where the phone number is being entered- Returns:
- an
AsYouTypeFormatter
object, which can be used to format phone numbers in the specific region "as you type"
-
parse
public Phonenumber.PhoneNumber parse(CharSequence numberToParse, String defaultRegion) throws NumberParseException Parses a string and returns it as a phone number in proto buffer format. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".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 withisValidNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)
.Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then call
parseAndKeepRawInput(java.lang.CharSequence, java.lang.String)
instead.- Parameters:
numberToParse
- number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format.defaultRegion
- region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then RegionCode.ZZ or null can be supplied.- Returns:
- a phone number proto buffer filled with the parsed number
- Throws:
NumberParseException
- if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +)
-
parse
public void parse(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber) throws NumberParseException Same asparse(CharSequence, String)
, but accepts mutable PhoneNumber as a parameter to decrease object creation when invoked many times.- Throws:
NumberParseException
-
parseAndKeepRawInput
public Phonenumber.PhoneNumber parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion) throws NumberParseException Parses a string and returns it in proto buffer format. This method differs fromparse(java.lang.CharSequence, java.lang.String)
in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.- Parameters:
numberToParse
- number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension.defaultRegion
- region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country calling code for the number in this case would be stored as that of the default region supplied.- Returns:
- a phone number proto buffer filled with the parsed number
- Throws:
NumberParseException
- if the string is not considered to be a viable phone number or if no default region was supplied
-
parseAndKeepRawInput
public void parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber) throws NumberParseException Same asparseAndKeepRawInput(CharSequence, String)
, but accepts a mutable PhoneNumber as a parameter to decrease object creation when invoked many times.- Throws:
NumberParseException
-
findNumbers
Returns an iterable over allPhoneNumberMatches
intext
. This is a shortcut forgetMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)
.- Parameters:
text
- the text to search for phone numbers, null for no textdefaultRegion
- region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. May be null if only international numbers are expected.
-
findNumbers
public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion, PhoneNumberUtil.Leniency leniency, long maxTries) Returns an iterable over allPhoneNumberMatches
intext
.- Parameters:
text
- the text to search for phone numbers, null for no textdefaultRegion
- region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. May be null if only international numbers are expected.leniency
- the leniency to use when evaluating candidate phone numbersmaxTries
- the maximum number of invalid numbers to try before giving up on the text. This is to cover degenerate cases where the text has a lot of false positives in it. Must be>= 0
.
-
isNumberMatch
public PhoneNumberUtil.MatchType isNumberMatch(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn) 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.
- Parameters:
firstNumberIn
- first number to comparesecondNumberIn
- second number to compare- Returns:
- NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality of the two numbers, described in the method definition.
-
isNumberMatch
Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper forisNumberMatch(PhoneNumber, PhoneNumber)
. No default region is known.- Parameters:
firstNumber
- first number to compare. Can contain formatting, and can have country calling code specified with + at the start.secondNumber
- second number to compare. Can contain formatting, and can have country calling code specified with + at the start.- Returns:
- NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
isNumberMatch(PhoneNumber, PhoneNumber)
for more details.
-
isNumberMatch
public PhoneNumberUtil.MatchType isNumberMatch(Phonenumber.PhoneNumber firstNumber, CharSequence secondNumber) Takes two phone numbers and compares them for equality. This is a convenience wrapper forisNumberMatch(PhoneNumber, PhoneNumber)
. No default region is known.- Parameters:
firstNumber
- first number to compare in proto buffer formatsecondNumber
- second number to compare. Can contain formatting, and can have country calling code specified with + at the start.- Returns:
- NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
isNumberMatch(PhoneNumber, PhoneNumber)
for more details.
-
canBeInternationallyDialled
Returns true if the number can be dialled from outside the region, or unknown. If the number can only be dialled from within the region, returns false. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country).- Parameters:
number
- the phone-number for which we want to know whether it is diallable from outside the region
-
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.- Parameters:
regionCode
- the region for which we want to know whether it supports mobile number portability or not
-