Home | History | Annotate | Download | only in phonenumbers
      1 /*
      2  * Copyright (C) 2009 The Libphonenumber Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.i18n.phonenumbers;
     18 
     19 import com.android.i18n.phonenumbers.Phonemetadata.NumberFormat;
     20 import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
     21 import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
     22 import com.android.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
     23 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber;
     24 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
     25 
     26 import java.io.IOException;
     27 import java.io.InputStream;
     28 import java.io.ObjectInputStream;
     29 import java.util.ArrayList;
     30 import java.util.Arrays;
     31 import java.util.Collections;
     32 import java.util.HashMap;
     33 import java.util.HashSet;
     34 import java.util.Iterator;
     35 import java.util.List;
     36 import java.util.Map;
     37 import java.util.Set;
     38 import java.util.logging.Level;
     39 import java.util.logging.Logger;
     40 import java.util.regex.Matcher;
     41 import java.util.regex.Pattern;
     42 
     43 /**
     44  * Utility for international phone numbers. Functionality includes formatting, parsing and
     45  * validation.
     46  *
     47  * <p>If you use this library, and want to be notified about important changes, please sign up to
     48  * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
     49  *
     50  * NOTE: A lot of methods in this class require Region Code strings. These must be provided using
     51  * ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes
     52  * can be found here: http://www.iso.org/iso/english_country_names_and_code_elements
     53  *
     54  * @author Shaopeng Jia
     55  * @author Lara Rennie
     56  */
     57 public class PhoneNumberUtil {
     58   /** Flags to use when compiling regular expressions for phone numbers. */
     59   static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
     60   // The minimum and maximum length of the national significant number.
     61   private static final int MIN_LENGTH_FOR_NSN = 3;
     62   // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
     63   static final int MAX_LENGTH_FOR_NSN = 16;
     64   // The maximum length of the country calling code.
     65   static final int MAX_LENGTH_COUNTRY_CODE = 3;
     66   // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
     67   // input from overflowing the regular-expression engine.
     68   private static final int MAX_INPUT_STRING_LENGTH = 250;
     69   static final String META_DATA_FILE_PREFIX =
     70       "/com/android/i18n/phonenumbers/data/PhoneNumberMetadataProto";
     71   private String currentFilePrefix = META_DATA_FILE_PREFIX;
     72   private static final Logger LOGGER = Logger.getLogger(PhoneNumberUtil.class.getName());
     73 
     74   // A mapping from a country calling code to the region codes which denote the region represented
     75   // by that country calling code. In the case of multiple regions sharing a calling code, such as
     76   // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
     77   // first.
     78   private Map<Integer, List<String>> countryCallingCodeToRegionCodeMap = null;
     79 
     80   // The set of regions the library supports.
     81   // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
     82   // load factor of roughly 0.75.
     83   private final Set<String> supportedRegions = new HashSet<String>(320);
     84 
     85   // Region-code for the unknown region.
     86   private static final String UNKNOWN_REGION = "ZZ";
     87 
     88   // The set of regions that share country calling code 1.
     89   // There are roughly 26 regions and we set the initial capacity of the HashSet to 35 to offer a
     90   // load factor of roughly 0.75.
     91   private final Set<String> nanpaRegions = new HashSet<String>(35);
     92   private static final int NANPA_COUNTRY_CODE = 1;
     93 
     94   // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
     95   // a mobile phone in Colombia.
     96   private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
     97 
     98   // The PLUS_SIGN signifies the international prefix.
     99   static final char PLUS_SIGN = '+';
    100 
    101   private static final char STAR_SIGN = '*';
    102 
    103   private static final String RFC3966_EXTN_PREFIX = ";ext=";
    104 
    105   // A map that contains characters that are essential when dialling. That means any of the
    106   // characters in this map must not be removed from a number when dialing, otherwise the call will
    107   // not reach the intended destination.
    108   private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
    109 
    110   // Only upper-case variants of alpha characters are stored.
    111   private static final Map<Character, Character> ALPHA_MAPPINGS;
    112 
    113   // For performance reasons, amalgamate both into one map.
    114   private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
    115 
    116   // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
    117   // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
    118   private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
    119 
    120   static {
    121     // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
    122     // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
    123     HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
    124     asciiDigitMappings.put('0', '0');
    125     asciiDigitMappings.put('1', '1');
    126     asciiDigitMappings.put('2', '2');
    127     asciiDigitMappings.put('3', '3');
    128     asciiDigitMappings.put('4', '4');
    129     asciiDigitMappings.put('5', '5');
    130     asciiDigitMappings.put('6', '6');
    131     asciiDigitMappings.put('7', '7');
    132     asciiDigitMappings.put('8', '8');
    133     asciiDigitMappings.put('9', '9');
    134 
    135     HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
    136     alphaMap.put('A', '2');
    137     alphaMap.put('B', '2');
    138     alphaMap.put('C', '2');
    139     alphaMap.put('D', '3');
    140     alphaMap.put('E', '3');
    141     alphaMap.put('F', '3');
    142     alphaMap.put('G', '4');
    143     alphaMap.put('H', '4');
    144     alphaMap.put('I', '4');
    145     alphaMap.put('J', '5');
    146     alphaMap.put('K', '5');
    147     alphaMap.put('L', '5');
    148     alphaMap.put('M', '6');
    149     alphaMap.put('N', '6');
    150     alphaMap.put('O', '6');
    151     alphaMap.put('P', '7');
    152     alphaMap.put('Q', '7');
    153     alphaMap.put('R', '7');
    154     alphaMap.put('S', '7');
    155     alphaMap.put('T', '8');
    156     alphaMap.put('U', '8');
    157     alphaMap.put('V', '8');
    158     alphaMap.put('W', '9');
    159     alphaMap.put('X', '9');
    160     alphaMap.put('Y', '9');
    161     alphaMap.put('Z', '9');
    162     ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
    163 
    164     HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
    165     combinedMap.putAll(ALPHA_MAPPINGS);
    166     combinedMap.putAll(asciiDigitMappings);
    167     ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
    168 
    169     HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
    170     diallableCharMap.putAll(asciiDigitMappings);
    171     diallableCharMap.put('+', '+');
    172     diallableCharMap.put('*', '*');
    173     DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
    174 
    175     HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
    176     // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
    177     for (char c : ALPHA_MAPPINGS.keySet()) {
    178       allPlusNumberGroupings.put(Character.toLowerCase(c), c);
    179       allPlusNumberGroupings.put(c, c);
    180     }
    181     allPlusNumberGroupings.putAll(asciiDigitMappings);
    182     // Put grouping symbols.
    183     allPlusNumberGroupings.put('-', '-');
    184     allPlusNumberGroupings.put('\uFF0D', '-');
    185     allPlusNumberGroupings.put('\u2010', '-');
    186     allPlusNumberGroupings.put('\u2011', '-');
    187     allPlusNumberGroupings.put('\u2012', '-');
    188     allPlusNumberGroupings.put('\u2013', '-');
    189     allPlusNumberGroupings.put('\u2014', '-');
    190     allPlusNumberGroupings.put('\u2015', '-');
    191     allPlusNumberGroupings.put('\u2212', '-');
    192     allPlusNumberGroupings.put('/', '/');
    193     allPlusNumberGroupings.put('\uFF0F', '/');
    194     allPlusNumberGroupings.put(' ', ' ');
    195     allPlusNumberGroupings.put('\u3000', ' ');
    196     allPlusNumberGroupings.put('\u2060', ' ');
    197     allPlusNumberGroupings.put('.', '.');
    198     allPlusNumberGroupings.put('\uFF0E', '.');
    199     ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
    200   }
    201 
    202   // Pattern that makes it easy to distinguish whether a region has a unique international dialing
    203   // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
    204   // represented as a string that contains a sequence of ASCII digits. If there are multiple
    205   // available international prefixes in a region, they will be represented as a regex string that
    206   // always contains character(s) other than ASCII digits.
    207   // Note this regex also includes tilde, which signals waiting for the tone.
    208   private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
    209       Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
    210 
    211   // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
    212   // found as a leading character only.
    213   // This consists of dash characters, white space characters, full stops, slashes,
    214   // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
    215   // placeholder for carrier information in some phone numbers. Full-width variants are also
    216   // present.
    217   static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
    218       "\u00A0\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
    219 
    220   private static final String DIGITS = "\\p{Nd}";
    221   // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
    222   private static final String VALID_ALPHA =
    223       Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
    224       Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
    225   static final String PLUS_CHARS = "+\uFF0B";
    226   static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
    227   private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
    228   private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
    229 
    230   // Regular expression of acceptable characters that may start a phone number for the purposes of
    231   // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
    232   // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
    233   // does not contain alpha characters, although they may be used later in the number. It also does
    234   // not include other punctuation, as this will be stripped later during parsing and is of no
    235   // information value when parsing a number.
    236   private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
    237   private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
    238 
    239   // Regular expression of characters typically used to start a second phone number for the purposes
    240   // of parsing. This allows us to strip off parts of the number that are actually the start of
    241   // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
    242   // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
    243   // extension so that the first number is parsed correctly.
    244   private static final String SECOND_NUMBER_START = "[\\\\/] *x";
    245   static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
    246 
    247   // Regular expression of trailing characters that we want to remove. We remove all characters that
    248   // are not alpha or numerical characters. The hash character is retained here, as it may signify
    249   // the previous block was an extension.
    250   private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
    251   static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
    252 
    253   // We use this pattern to check if the phone number has at least three letters in it - if so, then
    254   // we treat it as a number where some phone-number digits are represented by letters.
    255   private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
    256 
    257   // Regular expression of viable phone numbers. This is location independent. Checks we have at
    258   // least three leading digits, and only valid punctuation, alpha characters and
    259   // digits in the phone number. Does not include extension data.
    260   // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
    261   // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
    262   // the start.
    263   // Corresponds to the following:
    264   // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
    265   // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
    266   private static final String VALID_PHONE_NUMBER =
    267       "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
    268       VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
    269 
    270   // Default extension prefix to use when formatting. This will be put in front of any extension
    271   // component of the number, after the main national number is formatted. For example, if you wish
    272   // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
    273   // as the default extension prefix. This can be overridden by region-specific preferences.
    274   private static final String DEFAULT_EXTN_PREFIX = " ext. ";
    275 
    276   // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
    277   // extension.
    278   private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
    279   // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
    280   // case-insensitive regexp match. Wide character versions are also provided after each ASCII
    281   // version.
    282   private static final String EXTN_PATTERNS_FOR_PARSING;
    283   static final String EXTN_PATTERNS_FOR_MATCHING;
    284   static {
    285     // One-character symbols that can be used to indicate an extension.
    286     String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
    287     // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
    288     // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
    289     // indicate this.
    290     String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
    291 
    292     EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
    293     EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
    294   }
    295 
    296   /**
    297    * Helper initialiser method to create the regular-expression pattern to match extensions,
    298    * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
    299    */
    300   private static String createExtnPattern(String singleExtnSymbols) {
    301     // There are three regular expressions here. The first covers RFC 3966 format, where the
    302     // extension is added using ";ext=". The second more generic one starts with optional white
    303     // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
    304     // the numbers themselves. The other one covers the special case of American numbers where the
    305     // extension is written with a hash at the end, such as "- 503#".
    306     // Note that the only capturing groups should be around the digits that you want to capture as
    307     // part of the extension, or else parsing will fail!
    308     // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
    309     // for representing the accented o - the character itself, and one in the unicode decomposed
    310     // form with the combining acute accent.
    311     return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
    312             "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
    313             "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
    314             "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
    315             "[- ]+(" + DIGITS + "{1,5})#");
    316   }
    317 
    318   // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
    319   // digits, for use when parsing.
    320   private static final Pattern EXTN_PATTERN =
    321       Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
    322 
    323   // We append optionally the extension pattern to the end here, as a valid phone number may
    324   // have an extension prefix appended, followed by 1 or more digits.
    325   private static final Pattern VALID_PHONE_NUMBER_PATTERN =
    326       Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
    327 
    328   private static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
    329 
    330   // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
    331   // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
    332   // correctly.  Therefore, we use \d, so that the first group actually used in the pattern will be
    333   // matched.
    334   private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
    335   private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
    336   private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
    337   private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
    338 
    339   private static PhoneNumberUtil instance = null;
    340 
    341   // A mapping from a region code to the PhoneMetadata for that region.
    342   private final Map<String, PhoneMetadata> regionToMetadataMap =
    343       Collections.synchronizedMap(new HashMap<String, PhoneMetadata>());
    344 
    345   // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
    346   // that country calling code. Examples of the country calling codes include 800 (International
    347   // Toll Free Service) and 808 (International Shared Cost Service).
    348   private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
    349       Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>());
    350 
    351   // A cache for frequently used region-specific regular expressions.
    352   // As most people use phone numbers primarily from one to two countries, and there are roughly 60
    353   // regular expressions needed, the initial capacity of 100 offers a rough load factor of 0.75.
    354   private RegexCache regexCache = new RegexCache(100);
    355 
    356   public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
    357 
    358   /**
    359    * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
    360    * E123. For example, the number of the Google Switzerland office will be written as
    361    * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
    362    * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
    363    * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
    364    * separating symbols replaced with a hyphen, and with any phone number extension appended with
    365    * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
    366    *
    367    * Note: If you are considering storing the number in a neutral format, you are highly advised to
    368    * use the PhoneNumber class.
    369    */
    370   public enum PhoneNumberFormat {
    371     E164,
    372     INTERNATIONAL,
    373     NATIONAL,
    374     RFC3966
    375   }
    376 
    377   /**
    378    * Type of phone numbers.
    379    */
    380   public enum PhoneNumberType {
    381     FIXED_LINE,
    382     MOBILE,
    383     // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
    384     // mobile numbers by looking at the phone number itself.
    385     FIXED_LINE_OR_MOBILE,
    386     // Freephone lines
    387     TOLL_FREE,
    388     PREMIUM_RATE,
    389     // The cost of this call is shared between the caller and the recipient, and is hence typically
    390     // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
    391     // more information.
    392     SHARED_COST,
    393     // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
    394     VOIP,
    395     // A personal number is associated with a particular person, and may be routed to either a
    396     // MOBILE or FIXED_LINE number. Some more information can be found here:
    397     // http://en.wikipedia.org/wiki/Personal_Numbers
    398     PERSONAL_NUMBER,
    399     PAGER,
    400     // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
    401     // specific offices, but allow one number to be used for a company.
    402     UAN,
    403     // Used for "Voice Mail Access Numbers".
    404     VOICEMAIL,
    405     // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
    406     // specific region.
    407     UNKNOWN
    408   }
    409 
    410   /**
    411    * Types of phone number matches. See detailed description beside the isNumberMatch() method.
    412    */
    413   public enum MatchType {
    414     NOT_A_NUMBER,
    415     NO_MATCH,
    416     SHORT_NSN_MATCH,
    417     NSN_MATCH,
    418     EXACT_MATCH,
    419   }
    420 
    421   /**
    422    * Possible outcomes when testing if a PhoneNumber is possible.
    423    */
    424   public enum ValidationResult {
    425     IS_POSSIBLE,
    426     INVALID_COUNTRY_CODE,
    427     TOO_SHORT,
    428     TOO_LONG,
    429   }
    430 
    431   /**
    432    * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
    433    * segments. The levels here are ordered in increasing strictness.
    434    */
    435   public enum Leniency {
    436     /**
    437      * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
    438      * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
    439      */
    440     POSSIBLE {
    441       @Override
    442       boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
    443         return util.isPossibleNumber(number);
    444       }
    445     },
    446     /**
    447      * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
    448      * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
    449      * in national format must have their national-prefix present if it is usually written for a
    450      * number of this type.
    451      */
    452     VALID {
    453       @Override
    454       boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
    455         if (!util.isValidNumber(number) ||
    456             !containsOnlyValidXChars(number, candidate, util)) {
    457           return false;
    458         }
    459         return isNationalPrefixPresentIfRequired(number, util);
    460       }
    461     },
    462     /**
    463      * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
    464      * are grouped in a possible way for this locale. For example, a US number written as
    465      * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
    466      * "650 253 0000", "650 2530000" or "6502530000" are.
    467      * Numbers with more than one '/' symbol are also dropped at this level.
    468      * <p>
    469      * Warning: This level might result in lower coverage especially for regions outside of country
    470      * code "+1". If you are not sure about which level to use, email the discussion group
    471      * libphonenumber-discuss (at) googlegroups.com.
    472      */
    473     STRICT_GROUPING {
    474       @Override
    475       boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
    476         if (!util.isValidNumber(number) ||
    477             !containsOnlyValidXChars(number, candidate, util) ||
    478             containsMoreThanOneSlash(candidate) ||
    479             !isNationalPrefixPresentIfRequired(number, util)) {
    480           return false;
    481         }
    482         // TODO: Evaluate how this works for other locales (testing has been
    483         // limited to NANPA regions) and optimise if necessary.
    484         String[] formattedNumberGroups = getNationalNumberGroups(util, number);
    485         StringBuilder normalizedCandidate = normalizeDigits(candidate,
    486                                                             true /* keep strip non-digits */);
    487         int fromIndex = 0;
    488         // Check each group of consecutive digits are not broken into separate groups in the
    489         // {@code candidate} string.
    490         for (int i = 0; i < formattedNumberGroups.length; i++) {
    491           // Fails if the substring of {@code candidate} starting from {@code fromIndex} doesn't
    492           // contain the consecutive digits in formattedNumberGroups[i].
    493           fromIndex = normalizedCandidate.indexOf(formattedNumberGroups[i], fromIndex);
    494           if (fromIndex < 0) {
    495             return false;
    496           }
    497           // Moves {@code fromIndex} forward.
    498           fromIndex += formattedNumberGroups[i].length();
    499           if (i == 0 && fromIndex < normalizedCandidate.length()) {
    500             // We are at the position right after the NDC.
    501             if (Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
    502               // This means there is no formatting symbol after the NDC. In this case, we only
    503               // accept the number if there is no formatting symbol at all in the number, except
    504               // for extensions.
    505               String nationalSignificantNumber = util.getNationalSignificantNumber(number);
    506               return normalizedCandidate.substring(fromIndex - formattedNumberGroups[i].length())
    507                   .startsWith(nationalSignificantNumber);
    508             }
    509           }
    510         }
    511         // The check here makes sure that we haven't mistakenly already used the extension to
    512         // match the last group of the subscriber number. Note the extension cannot have
    513         // formatting in-between digits.
    514         return normalizedCandidate.substring(fromIndex).contains(number.getExtension());
    515       }
    516     },
    517     /**
    518      * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
    519      * are grouped in the same way that we would have formatted it, or as a single block. For
    520      * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
    521      * "650 253 0000" or "6502530000" are.
    522      * Numbers with more than one '/' symbol are also dropped at this level.
    523      * <p>
    524      * Warning: This level might result in lower coverage especially for regions outside of country
    525      * code "+1". If you are not sure about which level to use, email the discussion group
    526      * libphonenumber-discuss (at) googlegroups.com.
    527      */
    528     EXACT_GROUPING {
    529       @Override
    530       boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
    531         if (!util.isValidNumber(number) ||
    532             !containsOnlyValidXChars(number, candidate, util) ||
    533             containsMoreThanOneSlash(candidate) ||
    534             !isNationalPrefixPresentIfRequired(number, util)) {
    535           return false;
    536         }
    537         // TODO: Evaluate how this works for other locales (testing has been
    538         // limited to NANPA regions) and optimise if necessary.
    539         StringBuilder normalizedCandidate = normalizeDigits(candidate,
    540                                                             true /* keep strip non-digits */);
    541         String[] candidateGroups =
    542             NON_DIGITS_PATTERN.split(normalizedCandidate.toString());
    543         // Set this to the last group, skipping it if the number has an extension.
    544         int candidateNumberGroupIndex =
    545             number.hasExtension() ? candidateGroups.length - 2 : candidateGroups.length - 1;
    546         // First we check if the national significant number is formatted as a block.
    547         // We use contains and not equals, since the national significant number may be present with
    548         // a prefix such as a national number prefix, or the country code itself.
    549         if (candidateGroups.length == 1 ||
    550             candidateGroups[candidateNumberGroupIndex].contains(
    551                 util.getNationalSignificantNumber(number))) {
    552           return true;
    553         }
    554         String[] formattedNumberGroups = getNationalNumberGroups(util, number);
    555         // Starting from the end, go through in reverse, excluding the first group, and check the
    556         // candidate and number groups are the same.
    557         for (int formattedNumberGroupIndex = (formattedNumberGroups.length - 1);
    558              formattedNumberGroupIndex > 0 && candidateNumberGroupIndex >= 0;
    559              formattedNumberGroupIndex--, candidateNumberGroupIndex--) {
    560           if (!candidateGroups[candidateNumberGroupIndex].equals(
    561               formattedNumberGroups[formattedNumberGroupIndex])) {
    562             return false;
    563           }
    564         }
    565         // Now check the first group. There may be a national prefix at the start, so we only check
    566         // that the candidate group ends with the formatted number group.
    567         return (candidateNumberGroupIndex >= 0 &&
    568                 candidateGroups[candidateNumberGroupIndex].endsWith(formattedNumberGroups[0]));
    569       }
    570     };
    571 
    572     /**
    573      * Helper method to get the national-number part of a number, formatted without any national
    574      * prefix, and return it as a set of digit blocks that would be formatted together.
    575      */
    576     private static String[] getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number) {
    577       // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits.
    578       String rfc3966Format = util.format(number, PhoneNumberFormat.RFC3966);
    579       // We remove the extension part from the formatted string before splitting it into different
    580       // groups.
    581       int endIndex = rfc3966Format.indexOf(';');
    582       if (endIndex < 0) {
    583         endIndex = rfc3966Format.length();
    584       }
    585       // The country-code will have a '-' following it.
    586       int startIndex = rfc3966Format.indexOf('-') + 1;
    587       return rfc3966Format.substring(startIndex, endIndex).split("-");
    588     }
    589 
    590     private static boolean containsMoreThanOneSlash(String candidate) {
    591       int firstSlashIndex = candidate.indexOf('/');
    592       return (firstSlashIndex > 0 && candidate.substring(firstSlashIndex + 1).contains("/"));
    593     }
    594 
    595     private static boolean containsOnlyValidXChars(
    596         PhoneNumber number, String candidate, PhoneNumberUtil util) {
    597       // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the
    598       // national significant number or (2) an extension sign, in which case they always precede the
    599       // extension number. We assume a carrier code is more than 1 digit, so the first case has to
    600       // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1
    601       // 'x' or 'X'. We ignore the character if it appears as the last character of the string.
    602       for (int index = 0; index < candidate.length() - 1; index++) {
    603         char charAtIndex = candidate.charAt(index);
    604         if (charAtIndex == 'x' || charAtIndex == 'X') {
    605           char charAtNextIndex = candidate.charAt(index + 1);
    606           if (charAtNextIndex == 'x' || charAtNextIndex == 'X') {
    607             // This is the carrier code case, in which the 'X's always precede the national
    608             // significant number.
    609             index++;
    610             if (util.isNumberMatch(number, candidate.substring(index)) != MatchType.NSN_MATCH) {
    611               return false;
    612             }
    613           // This is the extension sign case, in which the 'x' or 'X' should always precede the
    614           // extension number.
    615           } else if (!PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(index)).equals(
    616               number.getExtension())) {
    617               return false;
    618           }
    619         }
    620       }
    621       return true;
    622     }
    623 
    624     private static boolean isNationalPrefixPresentIfRequired(
    625         PhoneNumber number, PhoneNumberUtil util) {
    626       // First, check how we deduced the country code. If it was written in international format,
    627       // then the national prefix is not required.
    628       if (number.getCountryCodeSource() != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
    629         return true;
    630       }
    631       String phoneNumberRegion =
    632           util.getRegionCodeForCountryCode(number.getCountryCode());
    633       PhoneMetadata metadata = util.getMetadataForRegion(phoneNumberRegion);
    634       if (metadata == null) {
    635         return true;
    636       }
    637       // Check if a national prefix should be present when formatting this number.
    638       String nationalNumber = util.getNationalSignificantNumber(number);
    639       NumberFormat formatRule =
    640           util.chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
    641       // To do this, we check that a national prefix formatting rule was present and that it wasn't
    642       // just the first-group symbol ($1) with punctuation.
    643       if ((formatRule != null) && formatRule.getNationalPrefixFormattingRule().length() > 0) {
    644         if (formatRule.isNationalPrefixOptionalWhenFormatting()) {
    645           // The national-prefix is optional in these cases, so we don't need to check if it was
    646           // present.
    647           return true;
    648         }
    649         // Remove the first-group symbol.
    650         String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
    651         // We assume that the first-group symbol will never be _before_ the national prefix.
    652         candidateNationalPrefixRule =
    653             candidateNationalPrefixRule.substring(0, candidateNationalPrefixRule.indexOf("$1"));
    654         candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
    655         if (candidateNationalPrefixRule.length() == 0) {
    656           // National Prefix not needed for this number.
    657           return true;
    658         }
    659         // Normalize the remainder.
    660         String rawInputCopy = normalizeDigitsOnly(number.getRawInput());
    661         StringBuilder rawInput = new StringBuilder(rawInputCopy);
    662         // Check if we found a national prefix and/or carrier code at the start of the raw input,
    663         // and return the result.
    664         return util.maybeStripNationalPrefixAndCarrierCode(rawInput, metadata, null);
    665       }
    666       return true;
    667     }
    668 
    669     /** Returns true if {@code number} is a verified number according to this leniency. */
    670     abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
    671   }
    672 
    673   /**
    674    * This class implements a singleton, so the only constructor is private.
    675    */
    676   private PhoneNumberUtil() {
    677   }
    678 
    679   private void init(String filePrefix) {
    680     currentFilePrefix = filePrefix;
    681     for (List<String> regionCodes : countryCallingCodeToRegionCodeMap.values()) {
    682       supportedRegions.addAll(regionCodes);
    683     }
    684     supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY);
    685     nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
    686   }
    687 
    688   private void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode) {
    689     boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
    690     InputStream source = isNonGeoRegion
    691         ? PhoneNumberUtil.class.getResourceAsStream(filePrefix + "_" + countryCallingCode)
    692         : PhoneNumberUtil.class.getResourceAsStream(filePrefix + "_" + regionCode);
    693     ObjectInputStream in = null;
    694     try {
    695       in = new ObjectInputStream(source);
    696       PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
    697       metadataCollection.readExternal(in);
    698       for (PhoneMetadata metadata : metadataCollection.getMetadataList()) {
    699         if (isNonGeoRegion) {
    700           countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);
    701         } else {
    702           regionToMetadataMap.put(regionCode, metadata);
    703         }
    704       }
    705     } catch (IOException e) {
    706       LOGGER.log(Level.WARNING, e.toString());
    707     } finally {
    708       close(in);
    709     }
    710   }
    711 
    712   private static void close(InputStream in) {
    713     if (in != null) {
    714       try {
    715         in.close();
    716       } catch (IOException e) {
    717         LOGGER.log(Level.WARNING, e.toString());
    718       }
    719     }
    720   }
    721 
    722   /**
    723    * Attempts to extract a possible number from the string passed in. This currently strips all
    724    * leading characters that cannot be used to start a phone number. Characters that can be used to
    725    * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
    726    * are found in the number passed in, an empty string is returned. This function also attempts to
    727    * strip off any alternative extensions or endings if two or more are present, such as in the case
    728    * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
    729    * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
    730    * number is parsed correctly.
    731    *
    732    * @param number  the string that might contain a phone number
    733    * @return        the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
    734    *                string if no character used to start phone numbers (such as + or any digit) is
    735    *                found in the number
    736    */
    737   static String extractPossibleNumber(String number) {
    738     Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
    739     if (m.find()) {
    740       number = number.substring(m.start());
    741       // Remove trailing non-alpha non-numerical characters.
    742       Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
    743       if (trailingCharsMatcher.find()) {
    744         number = number.substring(0, trailingCharsMatcher.start());
    745         LOGGER.log(Level.FINER, "Stripped trailing characters: " + number);
    746       }
    747       // Check for extra numbers at the end.
    748       Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
    749       if (secondNumber.find()) {
    750         number = number.substring(0, secondNumber.start());
    751       }
    752       return number;
    753     } else {
    754       return "";
    755     }
    756   }
    757 
    758   /**
    759    * Checks to see if the string of characters could possibly be a phone number at all. At the
    760    * moment, checks to see that the string begins with at least 3 digits, ignoring any punctuation
    761    * commonly found in phone numbers.
    762    * This method does not require the number to be normalized in advance - but does assume that
    763    * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
    764    *
    765    * @param number  string to be checked for viability as a phone number
    766    * @return        true if the number could be a phone number of some sort, otherwise false
    767    */
    768   // @VisibleForTesting
    769   static boolean isViablePhoneNumber(String number) {
    770     if (number.length() < MIN_LENGTH_FOR_NSN) {
    771       return false;
    772     }
    773     Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
    774     return m.matches();
    775   }
    776 
    777   /**
    778    * Normalizes a string of characters representing a phone number. This performs the following
    779    * conversions:
    780    *   Punctuation is stripped.
    781    *   For ALPHA/VANITY numbers:
    782    *   Letters are converted to their numeric representation on a telephone keypad. The keypad
    783    *       used here is the one defined in ITU Recommendation E.161. This is only done if there are
    784    *       3 or more letters in the number, to lessen the risk that such letters are typos.
    785    *   For other numbers:
    786    *   Wide-ascii digits are converted to normal ASCII (European) digits.
    787    *   Arabic-Indic numerals are converted to European numerals.
    788    *   Spurious alpha characters are stripped.
    789    *
    790    * @param number  a string of characters representing a phone number
    791    * @return        the normalized string version of the phone number
    792    */
    793   static String normalize(String number) {
    794     Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
    795     if (m.matches()) {
    796       return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
    797     } else {
    798       return normalizeDigitsOnly(number);
    799     }
    800   }
    801 
    802   /**
    803    * Normalizes a string of characters representing a phone number. This is a wrapper for
    804    * normalize(String number) but does in-place normalization of the StringBuilder provided.
    805    *
    806    * @param number  a StringBuilder of characters representing a phone number that will be
    807    *     normalized in place
    808    */
    809   static void normalize(StringBuilder number) {
    810     String normalizedNumber = normalize(number.toString());
    811     number.replace(0, number.length(), normalizedNumber);
    812   }
    813 
    814   /**
    815    * Normalizes a string of characters representing a phone number. This converts wide-ascii and
    816    * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
    817    *
    818    * @param number  a string of characters representing a phone number
    819    * @return        the normalized string version of the phone number
    820    */
    821   public static String normalizeDigitsOnly(String number) {
    822     return normalizeDigits(number, false /* strip non-digits */).toString();
    823   }
    824 
    825   private static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
    826     StringBuilder normalizedDigits = new StringBuilder(number.length());
    827     for (char c : number.toCharArray()) {
    828       int digit = Character.digit(c, 10);
    829       if (digit != -1) {
    830         normalizedDigits.append(digit);
    831       } else if (keepNonDigits) {
    832         normalizedDigits.append(c);
    833       }
    834     }
    835     return normalizedDigits;
    836   }
    837 
    838   /**
    839    * Converts all alpha characters in a number to their respective digits on a keypad, but retains
    840    * existing formatting.
    841    */
    842   public static String convertAlphaCharactersInNumber(String number) {
    843     return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
    844   }
    845 
    846   /**
    847    * Gets the length of the geographical area code in the {@code nationalNumber_} field of the
    848    * PhoneNumber object passed in, so that clients could use it to split a national significant
    849    * number into geographical area code and subscriber number. It works in such a way that the
    850    * resultant subscriber number should be diallable, at least on some devices. An example of how
    851    * this could be used:
    852    *
    853    * <pre>
    854    * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    855    * PhoneNumber number = phoneUtil.parse("16502530000", "US");
    856    * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
    857    * String areaCode;
    858    * String subscriberNumber;
    859    *
    860    * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
    861    * if (areaCodeLength > 0) {
    862    *   areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
    863    *   subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
    864    * } else {
    865    *   areaCode = "";
    866    *   subscriberNumber = nationalSignificantNumber;
    867    * }
    868    * </pre>
    869    *
    870    * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
    871    * using it for most purposes, but recommends using the more general {@code national_number}
    872    * instead. Read the following carefully before deciding to use this method:
    873    * <ul>
    874    *  <li> geographical area codes change over time, and this method honors those changes;
    875    *    therefore, it doesn't guarantee the stability of the result it produces.
    876    *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
    877    *    typically requires the full national_number to be dialled in most regions).
    878    *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
    879    *    entities
    880    *  <li> some geographical numbers have no area codes.
    881    * </ul>
    882    * @param number  the PhoneNumber object for which clients want to know the length of the area
    883    *     code.
    884    * @return  the length of area code of the PhoneNumber object passed in.
    885    */
    886   public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
    887     String regionCode = getRegionCodeForNumber(number);
    888     if (!isValidRegionCode(regionCode)) {
    889       return 0;
    890     }
    891     PhoneMetadata metadata = getMetadataForRegion(regionCode);
    892     if (!metadata.hasNationalPrefix()) {
    893       return 0;
    894     }
    895 
    896     PhoneNumberType type = getNumberTypeHelper(getNationalSignificantNumber(number),
    897                                                metadata);
    898     // Most numbers other than the two types below have to be dialled in full.
    899     if (type != PhoneNumberType.FIXED_LINE && type != PhoneNumberType.FIXED_LINE_OR_MOBILE) {
    900       return 0;
    901     }
    902 
    903     return getLengthOfNationalDestinationCode(number);
    904   }
    905 
    906   /**
    907    * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
    908    * so that clients could use it to split a national significant number into NDC and subscriber
    909    * number. The NDC of a phone number is normally the first group of digit(s) right after the
    910    * country calling code when the number is formatted in the international format, if there is a
    911    * subscriber number part that follows. An example of how this could be used:
    912    *
    913    * <pre>
    914    * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    915    * PhoneNumber number = phoneUtil.parse("18002530000", "US");
    916    * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
    917    * String nationalDestinationCode;
    918    * String subscriberNumber;
    919    *
    920    * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
    921    * if (nationalDestinationCodeLength > 0) {
    922    *   nationalDestinationCode = nationalSignificantNumber.substring(0,
    923    *       nationalDestinationCodeLength);
    924    *   subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
    925    * } else {
    926    *   nationalDestinationCode = "";
    927    *   subscriberNumber = nationalSignificantNumber;
    928    * }
    929    * </pre>
    930    *
    931    * Refer to the unittests to see the difference between this function and
    932    * {@link #getLengthOfGeographicalAreaCode}.
    933    *
    934    * @param number  the PhoneNumber object for which clients want to know the length of the NDC.
    935    * @return  the length of NDC of the PhoneNumber object passed in.
    936    */
    937   public int getLengthOfNationalDestinationCode(PhoneNumber number) {
    938     PhoneNumber copiedProto;
    939     if (number.hasExtension()) {
    940       // We don't want to alter the proto given to us, but we don't want to include the extension
    941       // when we format it, so we copy it and clear the extension here.
    942       copiedProto = new PhoneNumber();
    943       copiedProto.mergeFrom(number);
    944       copiedProto.clearExtension();
    945     } else {
    946       copiedProto = number;
    947     }
    948 
    949     String nationalSignificantNumber = format(copiedProto,
    950                                               PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
    951     String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
    952     // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
    953     // string (before the + symbol) and the second group will be the country calling code. The third
    954     // group will be area code if it is not the last group.
    955     if (numberGroups.length <= 3) {
    956       return 0;
    957     }
    958 
    959     if (getRegionCodeForCountryCode(number.getCountryCode()).equals("AR") &&
    960         getNumberType(number) == PhoneNumberType.MOBILE) {
    961       // Argentinian mobile numbers, when formatted in the international format, are in the form of
    962       // +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and add 1 for
    963       // the digit 9, which also forms part of the national significant number.
    964       //
    965       // TODO: Investigate the possibility of better modeling the metadata to make it
    966       // easier to obtain the NDC.
    967       return numberGroups[3].length() + 1;
    968     }
    969     return numberGroups[2].length();
    970   }
    971 
    972   /**
    973    * Normalizes a string of characters representing a phone number by replacing all characters found
    974    * in the accompanying map with the values therein, and stripping all other characters if
    975    * removeNonMatches is true.
    976    *
    977    * @param number                     a string of characters representing a phone number
    978    * @param normalizationReplacements  a mapping of characters to what they should be replaced by in
    979    *                                   the normalized version of the phone number
    980    * @param removeNonMatches           indicates whether characters that are not able to be replaced
    981    *                                   should be stripped from the number. If this is false, they
    982    *                                   will be left unchanged in the number.
    983    * @return  the normalized string version of the phone number
    984    */
    985   private static String normalizeHelper(String number,
    986                                         Map<Character, Character> normalizationReplacements,
    987                                         boolean removeNonMatches) {
    988     StringBuilder normalizedNumber = new StringBuilder(number.length());
    989     char[] numberAsCharArray = number.toCharArray();
    990     for (char character : numberAsCharArray) {
    991       Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
    992       if (newDigit != null) {
    993         normalizedNumber.append(newDigit);
    994       } else if (!removeNonMatches) {
    995         normalizedNumber.append(character);
    996       }
    997       // If neither of the above are true, we remove this character.
    998     }
    999     return normalizedNumber.toString();
   1000   }
   1001 
   1002   // @VisibleForTesting
   1003   static synchronized PhoneNumberUtil getInstance(
   1004       String baseFileLocation,
   1005       Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
   1006     if (instance == null) {
   1007       instance = new PhoneNumberUtil();
   1008       instance.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
   1009       instance.init(baseFileLocation);
   1010     }
   1011     return instance;
   1012   }
   1013 
   1014   /**
   1015    * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
   1016    */
   1017   // @VisibleForTesting
   1018   static synchronized void resetInstance() {
   1019     instance = null;
   1020   }
   1021 
   1022   /**
   1023    * Convenience method to get a list of what regions the library has metadata for.
   1024    */
   1025   public Set<String> getSupportedRegions() {
   1026     return supportedRegions;
   1027   }
   1028 
   1029   /**
   1030    * Convenience method to get a list of what global network calling codes the library has metadata
   1031    * for.
   1032    */
   1033   public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
   1034     return countryCodeToNonGeographicalMetadataMap.keySet();
   1035   }
   1036 
   1037   /**
   1038    * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
   1039    * parsing, or validation. The instance is loaded with phone number metadata for a number of most
   1040    * commonly used regions.
   1041    *
   1042    * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
   1043    * multiple times will only result in one instance being created.
   1044    *
   1045    * @return a PhoneNumberUtil instance
   1046    */
   1047   public static synchronized PhoneNumberUtil getInstance() {
   1048     if (instance == null) {
   1049       return getInstance(META_DATA_FILE_PREFIX,
   1050           CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
   1051     }
   1052     return instance;
   1053   }
   1054 
   1055   /**
   1056    * Helper function to check region code is not unknown or null.
   1057    */
   1058   private boolean isValidRegionCode(String regionCode) {
   1059     return regionCode != null && supportedRegions.contains(regionCode);
   1060   }
   1061 
   1062   /**
   1063    * Helper function to check the country calling code is valid.
   1064    */
   1065   private boolean hasValidCountryCallingCode(int countryCallingCode) {
   1066     return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
   1067   }
   1068 
   1069   /**
   1070    * Formats a phone number in the specified format using default rules. Note that this does not
   1071    * promise to produce a phone number that the user can dial from where they are - although we do
   1072    * format in either 'national' or 'international' format depending on what the client asks for, we
   1073    * do not currently support a more abbreviated format, such as for users in the same "area" who
   1074    * could potentially dial the number without area code. Note that if the phone number has a
   1075    * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
   1076    * which formatting rules to apply so we return the national significant number with no formatting
   1077    * applied.
   1078    *
   1079    * @param number         the phone number to be formatted
   1080    * @param numberFormat   the format the phone number should be formatted into
   1081    * @return  the formatted phone number
   1082    */
   1083   public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
   1084     if (number.getNationalNumber() == 0 && number.hasRawInput()) {
   1085       String rawInput = number.getRawInput();
   1086       if (rawInput.length() > 0) {
   1087         return rawInput;
   1088       }
   1089     }
   1090     StringBuilder formattedNumber = new StringBuilder(20);
   1091     format(number, numberFormat, formattedNumber);
   1092     return formattedNumber.toString();
   1093   }
   1094 
   1095   /**
   1096    * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
   1097    * a parameter to decrease object creation when invoked many times.
   1098    */
   1099   public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
   1100                      StringBuilder formattedNumber) {
   1101     // Clear the StringBuilder first.
   1102     formattedNumber.setLength(0);
   1103     int countryCallingCode = number.getCountryCode();
   1104     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1105     if (numberFormat == PhoneNumberFormat.E164) {
   1106       // Early exit for E164 case since no formatting of the national number needs to be applied.
   1107       // Extensions are not formatted.
   1108       formattedNumber.append(nationalSignificantNumber);
   1109       prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
   1110                                          formattedNumber);
   1111       return;
   1112     }
   1113     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
   1114     // share a country calling code is contained by only one region for performance reasons. For
   1115     // example, for NANPA regions it will be contained in the metadata for US.
   1116     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1117     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1118       formattedNumber.append(nationalSignificantNumber);
   1119       return;
   1120     }
   1121 
   1122     PhoneMetadata metadata =
   1123         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
   1124     formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
   1125     maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
   1126     prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
   1127   }
   1128 
   1129   /**
   1130    * Formats a phone number in the specified format using client-defined formatting rules. Note that
   1131    * if the phone number has a country calling code of zero or an otherwise invalid country calling
   1132    * code, we cannot work out things like whether there should be a national prefix applied, or how
   1133    * to format extensions, so we return the national significant number with no formatting applied.
   1134    *
   1135    * @param number                        the phone number to be formatted
   1136    * @param numberFormat                  the format the phone number should be formatted into
   1137    * @param userDefinedFormats            formatting rules specified by clients
   1138    * @return  the formatted phone number
   1139    */
   1140   public String formatByPattern(PhoneNumber number,
   1141                                 PhoneNumberFormat numberFormat,
   1142                                 List<NumberFormat> userDefinedFormats) {
   1143     int countryCallingCode = number.getCountryCode();
   1144     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1145     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
   1146     // share a country calling code is contained by only one region for performance reasons. For
   1147     // example, for NANPA regions it will be contained in the metadata for US.
   1148     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1149     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1150       return nationalSignificantNumber;
   1151     }
   1152     PhoneMetadata metadata =
   1153         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
   1154 
   1155     StringBuilder formattedNumber = new StringBuilder(20);
   1156 
   1157     NumberFormat formattingPattern =
   1158         chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
   1159     if (formattingPattern == null) {
   1160       // If no pattern above is matched, we format the number as a whole.
   1161       formattedNumber.append(nationalSignificantNumber);
   1162     } else {
   1163       NumberFormat numFormatCopy = new NumberFormat();
   1164       // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
   1165       // need to copy the rule so that subsequent replacements for different numbers have the
   1166       // appropriate national prefix.
   1167       numFormatCopy.mergeFrom(formattingPattern);
   1168       String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
   1169       if (nationalPrefixFormattingRule.length() > 0) {
   1170         String nationalPrefix = metadata.getNationalPrefix();
   1171         if (nationalPrefix.length() > 0) {
   1172           // Replace $NP with national prefix and $FG with the first group ($1).
   1173           nationalPrefixFormattingRule =
   1174               NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
   1175           nationalPrefixFormattingRule =
   1176               FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
   1177           numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
   1178         } else {
   1179           // We don't want to have a rule for how to format the national prefix if there isn't one.
   1180           numFormatCopy.clearNationalPrefixFormattingRule();
   1181         }
   1182       }
   1183       formattedNumber.append(
   1184           formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
   1185     }
   1186     maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
   1187     prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
   1188     return formattedNumber.toString();
   1189   }
   1190 
   1191   /**
   1192    * Formats a phone number in national format for dialing using the carrier as specified in the
   1193    * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
   1194    * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
   1195    * contains an empty string, returns the number in national format without any carrier code.
   1196    *
   1197    * @param number  the phone number to be formatted
   1198    * @param carrierCode  the carrier selection code to be used
   1199    * @return  the formatted phone number in national format for dialing using the carrier as
   1200    *          specified in the {@code carrierCode}
   1201    */
   1202   public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
   1203     int countryCallingCode = number.getCountryCode();
   1204     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1205     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
   1206     // share a country calling code is contained by only one region for performance reasons. For
   1207     // example, for NANPA regions it will be contained in the metadata for US.
   1208     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1209     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1210       return nationalSignificantNumber;
   1211     }
   1212 
   1213     StringBuilder formattedNumber = new StringBuilder(20);
   1214     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
   1215     formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
   1216                                      PhoneNumberFormat.NATIONAL, carrierCode));
   1217     maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
   1218     prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
   1219                                        formattedNumber);
   1220     return formattedNumber.toString();
   1221   }
   1222 
   1223   private PhoneMetadata getMetadataForRegionOrCallingCode(
   1224       int countryCallingCode, String regionCode) {
   1225     return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
   1226         ? getMetadataForNonGeographicalRegion(countryCallingCode)
   1227         : getMetadataForRegion(regionCode);
   1228   }
   1229 
   1230   /**
   1231    * Formats a phone number in national format for dialing using the carrier as specified in the
   1232    * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
   1233    * use the {@code fallbackCarrierCode} passed in instead. If there is no
   1234    * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
   1235    * string, return the number in national format without any carrier code.
   1236    *
   1237    * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
   1238    * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
   1239    *
   1240    * @param number  the phone number to be formatted
   1241    * @param fallbackCarrierCode  the carrier selection code to be used, if none is found in the
   1242    *     phone number itself
   1243    * @return  the formatted phone number in national format for dialing using the number's
   1244    *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
   1245    *     none is found
   1246    */
   1247   public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
   1248                                                              String fallbackCarrierCode) {
   1249     return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
   1250                                                        ? number.getPreferredDomesticCarrierCode()
   1251                                                        : fallbackCarrierCode);
   1252   }
   1253 
   1254   /**
   1255    * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
   1256    * specific region. If the number cannot be reached from the region (e.g. some countries block
   1257    * toll-free numbers from being called outside of the country), the method returns an empty
   1258    * string.
   1259    *
   1260    * @param number  the phone number to be formatted
   1261    * @param regionCallingFrom  the region where the call is being placed
   1262    * @param withFormatting  whether the number should be returned with formatting symbols, such as
   1263    *     spaces and dashes.
   1264    * @return  the formatted phone number
   1265    */
   1266   public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
   1267                                              boolean withFormatting) {
   1268     int countryCallingCode = number.getCountryCode();
   1269     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1270       return number.hasRawInput() ? number.getRawInput() : "";
   1271     }
   1272 
   1273     String formattedNumber;
   1274     // Clear the extension, as that part cannot normally be dialed together with the main number.
   1275     PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
   1276     PhoneNumberType numberType = getNumberType(numberNoExt);
   1277     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1278     if (regionCode.equals("CO") && regionCallingFrom.equals("CO")) {
   1279       if (numberType == PhoneNumberType.FIXED_LINE) {
   1280         formattedNumber =
   1281             formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
   1282       } else {
   1283         // E164 doesn't work at all when dialing within Colombia.
   1284         formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
   1285       }
   1286     } else if (regionCode.equals("PE") && regionCallingFrom.equals("PE")) {
   1287       // In Peru, numbers cannot be dialled using E164 format from a mobile phone for Movistar.
   1288       // Instead they must be dialled in national format.
   1289       formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
   1290     } else if (regionCode.equals("BR") && regionCallingFrom.equals("BR") &&
   1291         ((numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
   1292          (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE))) {
   1293       formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
   1294           ? formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
   1295           // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
   1296           // called within Brazil. Without that, most of the carriers won't connect the call.
   1297           // Because of that, we return an empty string here.
   1298           : "";
   1299     } else if (canBeInternationallyDialled(numberNoExt)) {
   1300       return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
   1301                             : format(numberNoExt, PhoneNumberFormat.E164);
   1302     } else {
   1303       formattedNumber = (regionCallingFrom.equals(regionCode))
   1304           ? format(numberNoExt, PhoneNumberFormat.NATIONAL) : "";
   1305     }
   1306     return withFormatting ? formattedNumber
   1307                           : normalizeHelper(formattedNumber, DIALLABLE_CHAR_MAPPINGS,
   1308                                             true /* remove non matches */);
   1309   }
   1310 
   1311   /**
   1312    * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
   1313    * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
   1314    * same as that of the region where the number is from, then NATIONAL formatting will be applied.
   1315    *
   1316    * <p>If the number itself has a country calling code of zero or an otherwise invalid country
   1317    * calling code, then we return the number with no formatting applied.
   1318    *
   1319    * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
   1320    * Kazakhstan (who share the same country calling code). In those cases, no international prefix
   1321    * is used. For regions which have multiple international prefixes, the number in its
   1322    * INTERNATIONAL format will be returned instead.
   1323    *
   1324    * @param number               the phone number to be formatted
   1325    * @param regionCallingFrom    the region where the call is being placed
   1326    * @return  the formatted phone number
   1327    */
   1328   public String formatOutOfCountryCallingNumber(PhoneNumber number,
   1329                                                 String regionCallingFrom) {
   1330     if (!isValidRegionCode(regionCallingFrom)) {
   1331       LOGGER.log(Level.WARNING,
   1332                  "Trying to format number from invalid region "
   1333                  + regionCallingFrom
   1334                  + ". International formatting applied.");
   1335       return format(number, PhoneNumberFormat.INTERNATIONAL);
   1336     }
   1337     int countryCallingCode = number.getCountryCode();
   1338     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1339     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1340       return nationalSignificantNumber;
   1341     }
   1342     if (countryCallingCode == NANPA_COUNTRY_CODE) {
   1343       if (isNANPACountry(regionCallingFrom)) {
   1344         // For NANPA regions, return the national format for these regions but prefix it with the
   1345         // country calling code.
   1346         return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
   1347       }
   1348     } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
   1349     // For regions that share a country calling code, the country calling code need not be dialled.
   1350     // This also applies when dialling within a region, so this if clause covers both these cases.
   1351     // Technically this is the case for dialling from La Reunion to other overseas departments of
   1352     // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
   1353     // edge case for now and for those cases return the version including country calling code.
   1354     // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
   1355       return format(number, PhoneNumberFormat.NATIONAL);
   1356     }
   1357     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
   1358     String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
   1359 
   1360     // For regions that have multiple international prefixes, the international format of the
   1361     // number is returned, unless there is a preferred international prefix.
   1362     String internationalPrefixForFormatting = "";
   1363     if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
   1364       internationalPrefixForFormatting = internationalPrefix;
   1365     } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
   1366       internationalPrefixForFormatting =
   1367           metadataForRegionCallingFrom.getPreferredInternationalPrefix();
   1368     }
   1369 
   1370     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1371     PhoneMetadata metadataForRegion =
   1372         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
   1373     String formattedNationalNumber =
   1374         formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
   1375     StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
   1376     maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
   1377                                   formattedNumber);
   1378     if (internationalPrefixForFormatting.length() > 0) {
   1379       formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
   1380           .insert(0, internationalPrefixForFormatting);
   1381     } else {
   1382       prefixNumberWithCountryCallingCode(countryCallingCode,
   1383                                          PhoneNumberFormat.INTERNATIONAL,
   1384                                          formattedNumber);
   1385     }
   1386     return formattedNumber.toString();
   1387   }
   1388 
   1389   /**
   1390    * Formats a phone number using the original phone number format that the number is parsed from.
   1391    * The original format is embedded in the country_code_source field of the PhoneNumber object
   1392    * passed in. If such information is missing, the number will be formatted into the NATIONAL
   1393    * format by default. When the number contains a leading zero and this is unexpected for this
   1394    * country, or we don't have a formatting pattern for the number, the method returns the raw input
   1395    * when it is available.
   1396    *
   1397    * Note this method guarantees no digit will be inserted, removed or modified as a result of
   1398    * formatting.
   1399    *
   1400    * @param number  the phone number that needs to be formatted in its original number format
   1401    * @param regionCallingFrom  the region whose IDD needs to be prefixed if the original number
   1402    *     has one
   1403    * @return  the formatted phone number in its original number format
   1404    */
   1405   public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
   1406     if (number.hasRawInput() &&
   1407         (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
   1408       // We check if we have the formatting pattern because without that, we might format the number
   1409       // as a group without national prefix.
   1410       return number.getRawInput();
   1411     }
   1412     if (!number.hasCountryCodeSource()) {
   1413       return format(number, PhoneNumberFormat.NATIONAL);
   1414     }
   1415     String formattedNumber;
   1416     switch (number.getCountryCodeSource()) {
   1417       case FROM_NUMBER_WITH_PLUS_SIGN:
   1418         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
   1419         break;
   1420       case FROM_NUMBER_WITH_IDD:
   1421         formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
   1422         break;
   1423       case FROM_NUMBER_WITHOUT_PLUS_SIGN:
   1424         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
   1425         break;
   1426       case FROM_DEFAULT_COUNTRY:
   1427         // Fall-through to default case.
   1428       default:
   1429         String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
   1430         // We strip non-digits from the NDD here, and from the raw input later, so that we can
   1431         // compare them easily.
   1432         String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
   1433         String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
   1434         if (nationalPrefix == null || nationalPrefix.length() == 0) {
   1435           // If the region doesn't have a national prefix at all, we can safely return the national
   1436           // format without worrying about a national prefix being added.
   1437           formattedNumber = nationalFormat;
   1438           break;
   1439         }
   1440         // Otherwise, we check if the original number was entered with a national prefix.
   1441         if (rawInputContainsNationalPrefix(
   1442             number.getRawInput(), nationalPrefix, regionCode)) {
   1443           // If so, we can safely return the national format.
   1444           formattedNumber = nationalFormat;
   1445           break;
   1446         }
   1447         PhoneMetadata metadata = getMetadataForRegion(regionCode);
   1448         String nationalNumber = getNationalSignificantNumber(number);
   1449         NumberFormat formatRule =
   1450             chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
   1451         // When the format we apply to this number doesn't contain national prefix, we can just
   1452         // return the national format.
   1453         // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
   1454         String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
   1455         // We assume that the first-group symbol will never be _before_ the national prefix.
   1456         int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
   1457         if (indexOfFirstGroup <= 0) {
   1458           formattedNumber = nationalFormat;
   1459           break;
   1460         }
   1461         candidateNationalPrefixRule =
   1462             candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
   1463         candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
   1464         if (candidateNationalPrefixRule.length() == 0) {
   1465           // National prefix not used when formatting this number.
   1466           formattedNumber = nationalFormat;
   1467           break;
   1468         }
   1469         // Otherwise, we need to remove the national prefix from our output.
   1470         NumberFormat numFormatCopy = new NumberFormat();
   1471         numFormatCopy.mergeFrom(formatRule);
   1472         numFormatCopy.clearNationalPrefixFormattingRule();
   1473         List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
   1474         numberFormats.add(numFormatCopy);
   1475         formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
   1476         break;
   1477     }
   1478     String rawInput = number.getRawInput();
   1479     // If no digit is inserted/removed/modified as a result of our formatting, we return the
   1480     // formatted phone number; otherwise we return the raw input the user entered.
   1481     return (formattedNumber != null &&
   1482             normalizeDigitsOnly(formattedNumber).equals(normalizeDigitsOnly(rawInput)))
   1483         ? formattedNumber
   1484         : rawInput;
   1485   }
   1486 
   1487   // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
   1488   // national prefix is assumed to be in digits-only form.
   1489   private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
   1490       String regionCode) {
   1491     String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
   1492     if (normalizedNationalNumber.startsWith(nationalPrefix)) {
   1493       try {
   1494         // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
   1495         // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
   1496         // check the validity of the number if the assumed national prefix is removed (777123 won't
   1497         // be valid in Japan).
   1498         return isValidNumber(
   1499             parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
   1500       } catch (NumberParseException e) {
   1501         return false;
   1502       }
   1503     }
   1504     return false;
   1505   }
   1506 
   1507   /**
   1508    * Returns true if a number is from a region whose national significant number couldn't contain a
   1509    * leading zero, but has the italian_leading_zero field set to true.
   1510    */
   1511   private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
   1512     return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
   1513   }
   1514 
   1515   private boolean hasFormattingPatternForNumber(PhoneNumber number) {
   1516     int countryCallingCode = number.getCountryCode();
   1517     String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
   1518     PhoneMetadata metadata =
   1519         getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
   1520     if (metadata == null) {
   1521       return false;
   1522     }
   1523     String nationalNumber = getNationalSignificantNumber(number);
   1524     NumberFormat formatRule =
   1525         chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
   1526     return formatRule != null;
   1527   }
   1528 
   1529   /**
   1530    * Formats a phone number for out-of-country dialing purposes.
   1531    *
   1532    * Note that in this version, if the number was entered originally using alpha characters and
   1533    * this version of the number is stored in raw_input, this representation of the number will be
   1534    * used rather than the digit representation. Grouping information, as specified by characters
   1535    * such as "-" and " ", will be retained.
   1536    *
   1537    * <p><b>Caveats:</b></p>
   1538    * <ul>
   1539    *  <li> This will not produce good results if the country calling code is both present in the raw
   1540    *       input _and_ is the start of the national number. This is not a problem in the regions
   1541    *       which typically use alpha numbers.
   1542    *  <li> This will also not produce good results if the raw input has any grouping information
   1543    *       within the first three digits of the national number, and if the function needs to strip
   1544    *       preceding digits/words in the raw input before these digits. Normally people group the
   1545    *       first three digits together so this is not a huge problem - and will be fixed if it
   1546    *       proves to be so.
   1547    * </ul>
   1548    *
   1549    * @param number  the phone number that needs to be formatted
   1550    * @param regionCallingFrom  the region where the call is being placed
   1551    * @return  the formatted phone number
   1552    */
   1553   public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
   1554                                                     String regionCallingFrom) {
   1555     String rawInput = number.getRawInput();
   1556     // If there is no raw input, then we can't keep alpha characters because there aren't any.
   1557     // In this case, we return formatOutOfCountryCallingNumber.
   1558     if (rawInput.length() == 0) {
   1559       return formatOutOfCountryCallingNumber(number, regionCallingFrom);
   1560     }
   1561     int countryCode = number.getCountryCode();
   1562     if (!hasValidCountryCallingCode(countryCode)) {
   1563       return rawInput;
   1564     }
   1565     // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
   1566     // the number in raw_input with the parsed number.
   1567     // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
   1568     // only.
   1569     rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
   1570     // Now we trim everything before the first three digits in the parsed number. We choose three
   1571     // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
   1572     // trim anything at all. Similarly, if the national number was less than three digits, we don't
   1573     // trim anything at all.
   1574     String nationalNumber = getNationalSignificantNumber(number);
   1575     if (nationalNumber.length() > 3) {
   1576       int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
   1577       if (firstNationalNumberDigit != -1) {
   1578         rawInput = rawInput.substring(firstNationalNumberDigit);
   1579       }
   1580     }
   1581     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
   1582     if (countryCode == NANPA_COUNTRY_CODE) {
   1583       if (isNANPACountry(regionCallingFrom)) {
   1584         return countryCode + " " + rawInput;
   1585       }
   1586     } else if (isValidRegionCode(regionCallingFrom) &&
   1587                countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
   1588       NumberFormat formattingPattern =
   1589           chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
   1590                                            nationalNumber);
   1591       if (formattingPattern == null) {
   1592         // If no pattern above is matched, we format the original input.
   1593         return rawInput;
   1594       }
   1595       NumberFormat newFormat = new NumberFormat();
   1596       newFormat.mergeFrom(formattingPattern);
   1597       // The first group is the first group of digits that the user wrote together.
   1598       newFormat.setPattern("(\\d+)(.*)");
   1599       // Here we just concatenate them back together after the national prefix has been fixed.
   1600       newFormat.setFormat("$1$2");
   1601       // Now we format using this pattern instead of the default pattern, but with the national
   1602       // prefix prefixed if necessary.
   1603       // This will not work in the cases where the pattern (and not the leading digits) decide
   1604       // whether a national prefix needs to be used, since we have overridden the pattern to match
   1605       // anything, but that is not the case in the metadata to date.
   1606       return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
   1607     }
   1608     String internationalPrefixForFormatting = "";
   1609     // If an unsupported region-calling-from is entered, or a country with multiple international
   1610     // prefixes, the international format of the number is returned, unless there is a preferred
   1611     // international prefix.
   1612     if (metadataForRegionCallingFrom != null) {
   1613       String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
   1614       internationalPrefixForFormatting =
   1615           UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
   1616           ? internationalPrefix
   1617           : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
   1618     }
   1619     StringBuilder formattedNumber = new StringBuilder(rawInput);
   1620     String regionCode = getRegionCodeForCountryCode(countryCode);
   1621     PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   1622     maybeAppendFormattedExtension(number, metadataForRegion,
   1623                                   PhoneNumberFormat.INTERNATIONAL, formattedNumber);
   1624     if (internationalPrefixForFormatting.length() > 0) {
   1625       formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
   1626           .insert(0, internationalPrefixForFormatting);
   1627     } else {
   1628       // Invalid region entered as country-calling-from (so no metadata was found for it) or the
   1629       // region chosen has multiple international dialling prefixes.
   1630       LOGGER.log(Level.WARNING,
   1631                  "Trying to format number from invalid region "
   1632                  + regionCallingFrom
   1633                  + ". International formatting applied.");
   1634       prefixNumberWithCountryCallingCode(countryCode,
   1635                                          PhoneNumberFormat.INTERNATIONAL,
   1636                                          formattedNumber);
   1637     }
   1638     return formattedNumber.toString();
   1639   }
   1640 
   1641   /**
   1642    * Gets the national significant number of the a phone number. Note a national significant number
   1643    * doesn't contain a national prefix or any formatting.
   1644    *
   1645    * @param number  the phone number for which the national significant number is needed
   1646    * @return  the national significant number of the PhoneNumber object passed in
   1647    */
   1648   public String getNationalSignificantNumber(PhoneNumber number) {
   1649     // If a leading zero has been set, we prefix this now. Note this is not a national prefix.
   1650     StringBuilder nationalNumber = new StringBuilder(number.isItalianLeadingZero() ? "0" : "");
   1651     nationalNumber.append(number.getNationalNumber());
   1652     return nationalNumber.toString();
   1653   }
   1654 
   1655   /**
   1656    * A helper function that is used by format and formatByPattern.
   1657    */
   1658   private void prefixNumberWithCountryCallingCode(int countryCallingCode,
   1659                                                   PhoneNumberFormat numberFormat,
   1660                                                   StringBuilder formattedNumber) {
   1661     switch (numberFormat) {
   1662       case E164:
   1663         formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
   1664         return;
   1665       case INTERNATIONAL:
   1666         formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
   1667         return;
   1668       case RFC3966:
   1669         formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
   1670             .insert(0, "tel:");
   1671         return;
   1672       case NATIONAL:
   1673       default:
   1674         return;
   1675     }
   1676   }
   1677 
   1678   // Simple wrapper of formatNsn for the common case of no carrier code.
   1679   private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
   1680     return formatNsn(number, metadata, numberFormat, null);
   1681   }
   1682 
   1683   // Note in some regions, the national number can be written in two completely different ways
   1684   // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
   1685   // numberFormat parameter here is used to specify which format to use for those cases. If a
   1686   // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
   1687   private String formatNsn(String number,
   1688                            PhoneMetadata metadata,
   1689                            PhoneNumberFormat numberFormat,
   1690                            String carrierCode) {
   1691     List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
   1692     // When the intlNumberFormats exists, we use that to format national number for the
   1693     // INTERNATIONAL format instead of using the numberDesc.numberFormats.
   1694     List<NumberFormat> availableFormats =
   1695         (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
   1696         ? metadata.numberFormats()
   1697         : metadata.intlNumberFormats();
   1698     NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
   1699     return (formattingPattern == null)
   1700         ? number
   1701         : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
   1702   }
   1703 
   1704   private NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
   1705                                                         String nationalNumber) {
   1706     for (NumberFormat numFormat : availableFormats) {
   1707       int size = numFormat.leadingDigitsPatternSize();
   1708       if (size == 0 || regexCache.getPatternForRegex(
   1709               // We always use the last leading_digits_pattern, as it is the most detailed.
   1710               numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
   1711         Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
   1712         if (m.matches()) {
   1713           return numFormat;
   1714         }
   1715       }
   1716     }
   1717     return null;
   1718   }
   1719 
   1720   // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
   1721   private String formatNsnUsingPattern(String nationalNumber,
   1722                                        NumberFormat formattingPattern,
   1723                                        PhoneNumberFormat numberFormat) {
   1724     return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
   1725   }
   1726 
   1727   // Note that carrierCode is optional - if NULL or an empty string, no carrier code replacement
   1728   // will take place.
   1729   private String formatNsnUsingPattern(String nationalNumber,
   1730                                        NumberFormat formattingPattern,
   1731                                        PhoneNumberFormat numberFormat,
   1732                                        String carrierCode) {
   1733     String numberFormatRule = formattingPattern.getFormat();
   1734     Matcher m =
   1735         regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
   1736     String formattedNationalNumber = "";
   1737     if (numberFormat == PhoneNumberFormat.NATIONAL &&
   1738         carrierCode != null && carrierCode.length() > 0 &&
   1739         formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
   1740       // Replace the $CC in the formatting rule with the desired carrier code.
   1741       String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
   1742       carrierCodeFormattingRule =
   1743           CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
   1744       // Now replace the $FG in the formatting rule with the first group and the carrier code
   1745       // combined in the appropriate way.
   1746       numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
   1747           .replaceFirst(carrierCodeFormattingRule);
   1748       formattedNationalNumber = m.replaceAll(numberFormatRule);
   1749     } else {
   1750       // Use the national prefix formatting rule instead.
   1751       String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
   1752       if (numberFormat == PhoneNumberFormat.NATIONAL &&
   1753           nationalPrefixFormattingRule != null &&
   1754           nationalPrefixFormattingRule.length() > 0) {
   1755         Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
   1756         formattedNationalNumber =
   1757             m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
   1758       } else {
   1759         formattedNationalNumber = m.replaceAll(numberFormatRule);
   1760       }
   1761     }
   1762     if (numberFormat == PhoneNumberFormat.RFC3966) {
   1763       // Strip any leading punctuation.
   1764       Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
   1765       if (matcher.lookingAt()) {
   1766         formattedNationalNumber = matcher.replaceFirst("");
   1767       }
   1768       // Replace the rest with a dash between each number group.
   1769       formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
   1770     }
   1771     return formattedNationalNumber;
   1772   }
   1773 
   1774   /**
   1775    * Gets a valid number for the specified region.
   1776    *
   1777    * @param regionCode  the region for which an example number is needed
   1778    * @return  a valid fixed-line number for the specified region. Returns null when the metadata
   1779    *    does not contain such information, or the region 001 is passed in. For 001 (representing
   1780    *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
   1781    */
   1782   public PhoneNumber getExampleNumber(String regionCode) {
   1783     return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
   1784   }
   1785 
   1786   /**
   1787    * Gets a valid number for the specified region and number type.
   1788    *
   1789    * @param regionCode  the region for which an example number is needed
   1790    * @param type  the type of number that is needed
   1791    * @return  a valid number for the specified region and type. Returns null when the metadata
   1792    *     does not contain such information or if an invalid region or region 001 was entered.
   1793    *     For 001 (representing non-geographical numbers), call
   1794    *     {@link #getExampleNumberForNonGeoEntity} instead.
   1795    */
   1796   public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
   1797     // Check the region code is valid.
   1798     if (!isValidRegionCode(regionCode)) {
   1799       LOGGER.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
   1800       return null;
   1801     }
   1802     PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
   1803     try {
   1804       if (desc.hasExampleNumber()) {
   1805         return parse(desc.getExampleNumber(), regionCode);
   1806       }
   1807     } catch (NumberParseException e) {
   1808       LOGGER.log(Level.SEVERE, e.toString());
   1809     }
   1810     return null;
   1811   }
   1812 
   1813   /**
   1814    * Gets a valid number for the specified country calling code for a non-geographical entity.
   1815    *
   1816    * @param countryCallingCode  the country calling code for a non-geographical entity
   1817    * @return  a valid number for the non-geographical entity. Returns null when the metadata
   1818    *    does not contain such information, or the country calling code passed in does not belong
   1819    *    to a non-geographical entity.
   1820    */
   1821   public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
   1822     PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
   1823     if (metadata != null) {
   1824       PhoneNumberDesc desc = metadata.getGeneralDesc();
   1825       try {
   1826         if (desc.hasExampleNumber()) {
   1827           return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
   1828         }
   1829       } catch (NumberParseException e) {
   1830         LOGGER.log(Level.SEVERE, e.toString());
   1831       }
   1832     } else {
   1833       LOGGER.log(Level.WARNING,
   1834                  "Invalid or unknown country calling code provided: " + countryCallingCode);
   1835     }
   1836     return null;
   1837   }
   1838 
   1839   /**
   1840    * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
   1841    * an extension specified.
   1842    */
   1843   private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
   1844                                              PhoneNumberFormat numberFormat,
   1845                                              StringBuilder formattedNumber) {
   1846     if (number.hasExtension() && number.getExtension().length() > 0) {
   1847       if (numberFormat == PhoneNumberFormat.RFC3966) {
   1848         formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
   1849       } else {
   1850         if (metadata.hasPreferredExtnPrefix()) {
   1851           formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
   1852         } else {
   1853           formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
   1854         }
   1855       }
   1856     }
   1857   }
   1858 
   1859   PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
   1860     switch (type) {
   1861       case PREMIUM_RATE:
   1862         return metadata.getPremiumRate();
   1863       case TOLL_FREE:
   1864         return metadata.getTollFree();
   1865       case MOBILE:
   1866         return metadata.getMobile();
   1867       case FIXED_LINE:
   1868       case FIXED_LINE_OR_MOBILE:
   1869         return metadata.getFixedLine();
   1870       case SHARED_COST:
   1871         return metadata.getSharedCost();
   1872       case VOIP:
   1873         return metadata.getVoip();
   1874       case PERSONAL_NUMBER:
   1875         return metadata.getPersonalNumber();
   1876       case PAGER:
   1877         return metadata.getPager();
   1878       case UAN:
   1879         return metadata.getUan();
   1880       case VOICEMAIL:
   1881         return metadata.getVoicemail();
   1882       default:
   1883         return metadata.getGeneralDesc();
   1884     }
   1885   }
   1886 
   1887   /**
   1888    * Gets the type of a phone number.
   1889    *
   1890    * @param number  the phone number that we want to know the type
   1891    * @return  the type of the phone number
   1892    */
   1893   public PhoneNumberType getNumberType(PhoneNumber number) {
   1894     String regionCode = getRegionCodeForNumber(number);
   1895     if (!isValidRegionCode(regionCode) && !REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)) {
   1896       return PhoneNumberType.UNKNOWN;
   1897     }
   1898     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1899     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
   1900     return getNumberTypeHelper(nationalSignificantNumber, metadata);
   1901   }
   1902 
   1903   private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
   1904     PhoneNumberDesc generalNumberDesc = metadata.getGeneralDesc();
   1905     if (!generalNumberDesc.hasNationalNumberPattern() ||
   1906         !isNumberMatchingDesc(nationalNumber, generalNumberDesc)) {
   1907       return PhoneNumberType.UNKNOWN;
   1908     }
   1909 
   1910     if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
   1911       return PhoneNumberType.PREMIUM_RATE;
   1912     }
   1913     if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
   1914       return PhoneNumberType.TOLL_FREE;
   1915     }
   1916     if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
   1917       return PhoneNumberType.SHARED_COST;
   1918     }
   1919     if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
   1920       return PhoneNumberType.VOIP;
   1921     }
   1922     if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
   1923       return PhoneNumberType.PERSONAL_NUMBER;
   1924     }
   1925     if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
   1926       return PhoneNumberType.PAGER;
   1927     }
   1928     if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
   1929       return PhoneNumberType.UAN;
   1930     }
   1931     if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
   1932       return PhoneNumberType.VOICEMAIL;
   1933     }
   1934 
   1935     boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
   1936     if (isFixedLine) {
   1937       if (metadata.isSameMobileAndFixedLinePattern()) {
   1938         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
   1939       } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
   1940         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
   1941       }
   1942       return PhoneNumberType.FIXED_LINE;
   1943     }
   1944     // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
   1945     // mobile and fixed line aren't the same.
   1946     if (!metadata.isSameMobileAndFixedLinePattern() &&
   1947         isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
   1948       return PhoneNumberType.MOBILE;
   1949     }
   1950     return PhoneNumberType.UNKNOWN;
   1951   }
   1952 
   1953   PhoneMetadata getMetadataForRegion(String regionCode) {
   1954     if (!isValidRegionCode(regionCode)) {
   1955       return null;
   1956     }
   1957     synchronized (regionToMetadataMap) {
   1958       if (!regionToMetadataMap.containsKey(regionCode)) {
   1959         // The regionCode here will be valid and won't be '001', so we don't need to worry about
   1960         // what to pass in for the country calling code.
   1961         loadMetadataFromFile(currentFilePrefix, regionCode, 0);
   1962       }
   1963     }
   1964     return regionToMetadataMap.get(regionCode);
   1965   }
   1966 
   1967   PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
   1968     synchronized (countryCodeToNonGeographicalMetadataMap) {
   1969       if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
   1970         return null;
   1971       }
   1972       if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
   1973         loadMetadataFromFile(currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode);
   1974       }
   1975     }
   1976     return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
   1977   }
   1978 
   1979   private boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
   1980     Matcher possibleNumberPatternMatcher =
   1981         regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
   1982             .matcher(nationalNumber);
   1983     Matcher nationalNumberPatternMatcher =
   1984         regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
   1985             .matcher(nationalNumber);
   1986     return possibleNumberPatternMatcher.matches() && nationalNumberPatternMatcher.matches();
   1987   }
   1988 
   1989   /**
   1990    * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
   1991    * is actually in use, which is impossible to tell by just looking at a number itself.
   1992    *
   1993    * @param number       the phone number that we want to validate
   1994    * @return  a boolean that indicates whether the number is of a valid pattern
   1995    */
   1996   public boolean isValidNumber(PhoneNumber number) {
   1997     String regionCode = getRegionCodeForNumber(number);
   1998     return isValidNumberForRegion(number, regionCode);
   1999   }
   2000 
   2001   /**
   2002    * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
   2003    * is actually in use, which is impossible to tell by just looking at a number itself. If the
   2004    * country calling code is not the same as the country calling code for the region, this
   2005    * immediately exits with false. After this, the specific number pattern rules for the region are
   2006    * examined. This is useful for determining for example whether a particular number is valid for
   2007    * Canada, rather than just a valid NANPA number.
   2008    *
   2009    * @param number       the phone number that we want to validate
   2010    * @param regionCode   the region that we want to validate the phone number for
   2011    * @return  a boolean that indicates whether the number is of a valid pattern
   2012    */
   2013   public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
   2014     int countryCode = number.getCountryCode();
   2015     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   2016     if ((metadata == null) ||
   2017         (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
   2018          countryCode != getCountryCodeForValidRegion(regionCode))) {
   2019       // Either the region code was invalid, or the country calling code for this number does not
   2020       // match that of the region code.
   2021       return false;
   2022     }
   2023     PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
   2024     String nationalSignificantNumber = getNationalSignificantNumber(number);
   2025 
   2026     // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in
   2027     // as a valid number if its national significant number is between the minimum and maximum
   2028     // lengths defined by ITU for a national significant number.
   2029     if (!generalNumDesc.hasNationalNumberPattern()) {
   2030       int numberLength = nationalSignificantNumber.length();
   2031       return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN;
   2032     }
   2033     return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
   2034   }
   2035 
   2036   /**
   2037    * Returns the region where a phone number is from. This could be used for geocoding at the region
   2038    * level.
   2039    *
   2040    * @param number  the phone number whose origin we want to know
   2041    * @return  the region where the phone number is from, or null if no region matches this calling
   2042    *     code
   2043    */
   2044   public String getRegionCodeForNumber(PhoneNumber number) {
   2045     int countryCode = number.getCountryCode();
   2046     List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
   2047     if (regions == null) {
   2048       String numberString = getNationalSignificantNumber(number);
   2049       LOGGER.log(Level.WARNING,
   2050                  "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
   2051       return null;
   2052     }
   2053     if (regions.size() == 1) {
   2054       return regions.get(0);
   2055     } else {
   2056       return getRegionCodeForNumberFromRegionList(number, regions);
   2057     }
   2058   }
   2059 
   2060   private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
   2061                                                       List<String> regionCodes) {
   2062     String nationalNumber = getNationalSignificantNumber(number);
   2063     for (String regionCode : regionCodes) {
   2064       // If leadingDigits is present, use this. Otherwise, do full validation.
   2065       PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2066       if (metadata.hasLeadingDigits()) {
   2067         if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
   2068                 .matcher(nationalNumber).lookingAt()) {
   2069           return regionCode;
   2070         }
   2071       } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
   2072         return regionCode;
   2073       }
   2074     }
   2075     return null;
   2076   }
   2077 
   2078   /**
   2079    * Returns the region code that matches the specific country calling code. In the case of no
   2080    * region code being found, ZZ will be returned. In the case of multiple regions, the one
   2081    * designated in the metadata as the "main" region for this calling code will be returned.
   2082    */
   2083   public String getRegionCodeForCountryCode(int countryCallingCode) {
   2084     List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
   2085     return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
   2086   }
   2087 
   2088   /**
   2089    * Returns the country calling code for a specific region. For example, this would be 1 for the
   2090    * United States, and 64 for New Zealand.
   2091    *
   2092    * @param regionCode  the region that we want to get the country calling code for
   2093    * @return  the country calling code for the region denoted by regionCode
   2094    */
   2095   public int getCountryCodeForRegion(String regionCode) {
   2096     if (!isValidRegionCode(regionCode)) {
   2097       LOGGER.log(Level.WARNING,
   2098                  "Invalid or missing region code ("
   2099                   + ((regionCode == null) ? "null" : regionCode)
   2100                   + ") provided.");
   2101       return 0;
   2102     }
   2103     return getCountryCodeForValidRegion(regionCode);
   2104   }
   2105 
   2106   /**
   2107    * Returns the country calling code for a specific region. For example, this would be 1 for the
   2108    * United States, and 64 for New Zealand. Assumes the region is already valid.
   2109    *
   2110    * @param regionCode  the region that we want to get the country calling code for
   2111    * @return  the country calling code for the region denoted by regionCode
   2112    */
   2113   private int getCountryCodeForValidRegion(String regionCode) {
   2114     PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2115     return metadata.getCountryCode();
   2116   }
   2117 
   2118   /**
   2119    * Returns the national dialling prefix for a specific region. For example, this would be 1 for
   2120    * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
   2121    * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
   2122    * present, we return null.
   2123    *
   2124    * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
   2125    * national dialling prefix is used only for certain types of numbers. Use the library's
   2126    * formatting functions to prefix the national prefix when required.
   2127    *
   2128    * @param regionCode  the region that we want to get the dialling prefix for
   2129    * @param stripNonDigits  true to strip non-digits from the national dialling prefix
   2130    * @return  the dialling prefix for the region denoted by regionCode
   2131    */
   2132   public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
   2133     if (!isValidRegionCode(regionCode)) {
   2134       LOGGER.log(Level.WARNING,
   2135                  "Invalid or missing region code ("
   2136                   + ((regionCode == null) ? "null" : regionCode)
   2137                   + ") provided.");
   2138       return null;
   2139     }
   2140     PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2141     String nationalPrefix = metadata.getNationalPrefix();
   2142     // If no national prefix was found, we return null.
   2143     if (nationalPrefix.length() == 0) {
   2144       return null;
   2145     }
   2146     if (stripNonDigits) {
   2147       // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
   2148       // to be removed here as well.
   2149       nationalPrefix = nationalPrefix.replace("~", "");
   2150     }
   2151     return nationalPrefix;
   2152   }
   2153 
   2154   /**
   2155    * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
   2156    *
   2157    * @return  true if regionCode is one of the regions under NANPA
   2158    */
   2159   public boolean isNANPACountry(String regionCode) {
   2160     return nanpaRegions.contains(regionCode);
   2161   }
   2162 
   2163   /**
   2164    * Checks whether the country calling code is from a region whose national significant number
   2165    * could contain a leading zero. An example of such a region is Italy. Returns false if no
   2166    * metadata for the country is found.
   2167    */
   2168   boolean isLeadingZeroPossible(int countryCallingCode) {
   2169     PhoneMetadata mainMetadataForCallingCode = getMetadataForRegion(
   2170         getRegionCodeForCountryCode(countryCallingCode));
   2171     if (mainMetadataForCallingCode == null) {
   2172       return false;
   2173     }
   2174     return mainMetadataForCallingCode.isLeadingZeroPossible();
   2175   }
   2176 
   2177   /**
   2178    * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
   2179    * number will start with at least 3 digits and will have three or more alpha characters. This
   2180    * does not do region-specific checks - to work out if this number is actually valid for a region,
   2181    * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
   2182    * {@link #isValidNumber} should be used.
   2183    *
   2184    * @param number  the number that needs to be checked
   2185    * @return  true if the number is a valid vanity number
   2186    */
   2187   public boolean isAlphaNumber(String number) {
   2188     if (!isViablePhoneNumber(number)) {
   2189       // Number is too short, or doesn't match the basic phone number pattern.
   2190       return false;
   2191     }
   2192     StringBuilder strippedNumber = new StringBuilder(number);
   2193     maybeStripExtension(strippedNumber);
   2194     return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
   2195   }
   2196 
   2197   /**
   2198    * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
   2199    * for failure, this method returns a boolean value.
   2200    * @param number  the number that needs to be checked
   2201    * @return  true if the number is possible
   2202    */
   2203   public boolean isPossibleNumber(PhoneNumber number) {
   2204     return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
   2205   }
   2206 
   2207   /**
   2208    * Helper method to check a number against a particular pattern and determine whether it matches,
   2209    * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
   2210    * and 10 are possible, and a number in between these possible lengths is entered, such as of
   2211    * length 8, this will return TOO_LONG.
   2212    */
   2213   private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
   2214     Matcher numberMatcher = numberPattern.matcher(number);
   2215     if (numberMatcher.matches()) {
   2216       return ValidationResult.IS_POSSIBLE;
   2217     }
   2218     if (numberMatcher.lookingAt()) {
   2219       return ValidationResult.TOO_LONG;
   2220     } else {
   2221       return ValidationResult.TOO_SHORT;
   2222     }
   2223   }
   2224 
   2225   /**
   2226    * Check whether a phone number is a possible number. It provides a more lenient check than
   2227    * {@link #isValidNumber} in the following sense:
   2228    *<ol>
   2229    * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
   2230    *      digits of the number.
   2231    * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
   2232    *      applies to all types of phone numbers in a region. Therefore, it is much faster than
   2233    *      isValidNumber.
   2234    * <li> For fixed line numbers, many regions have the concept of area code, which together with
   2235    *      subscriber number constitute the national significant number. It is sometimes okay to dial
   2236    *      the subscriber number only when dialing in the same area. This function will return
   2237    *      true if the subscriber-number-only version is passed in. On the other hand, because
   2238    *      isValidNumber validates using information on both starting digits (for fixed line
   2239    *      numbers, that would most likely be area codes) and length (obviously includes the
   2240    *      length of area codes for fixed line numbers), it will return false for the
   2241    *      subscriber-number-only version.
   2242    * </ol
   2243    * @param number  the number that needs to be checked
   2244    * @return  a ValidationResult object which indicates whether the number is possible
   2245    */
   2246   public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
   2247     String nationalNumber = getNationalSignificantNumber(number);
   2248     int countryCode = number.getCountryCode();
   2249     // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
   2250     // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
   2251     // valid. This would need to be revisited if the possible number pattern ever differed between
   2252     // various regions within those plans.
   2253     if (!hasValidCountryCallingCode(countryCode)) {
   2254       return ValidationResult.INVALID_COUNTRY_CODE;
   2255     }
   2256     String regionCode = getRegionCodeForCountryCode(countryCode);
   2257     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   2258     PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
   2259     // Handling case of numbers with no metadata.
   2260     if (!generalNumDesc.hasNationalNumberPattern()) {
   2261       LOGGER.log(Level.FINER, "Checking if number is possible with incomplete metadata.");
   2262       int numberLength = nationalNumber.length();
   2263       if (numberLength < MIN_LENGTH_FOR_NSN) {
   2264         return ValidationResult.TOO_SHORT;
   2265       } else if (numberLength > MAX_LENGTH_FOR_NSN) {
   2266         return ValidationResult.TOO_LONG;
   2267       } else {
   2268         return ValidationResult.IS_POSSIBLE;
   2269       }
   2270     }
   2271     Pattern possibleNumberPattern =
   2272         regexCache.getPatternForRegex(generalNumDesc.getPossibleNumberPattern());
   2273     return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
   2274   }
   2275 
   2276   /**
   2277    * Check whether a phone number is a possible number given a number in the form of a string, and
   2278    * the region where the number could be dialed from. It provides a more lenient check than
   2279    * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
   2280    *
   2281    * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
   2282    * with the resultant PhoneNumber object.
   2283    *
   2284    * @param number  the number that needs to be checked, in the form of a string
   2285    * @param regionDialingFrom  the region that we are expecting the number to be dialed from.
   2286    *     Note this is different from the region where the number belongs.  For example, the number
   2287    *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
   2288    *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
   2289    *     region which uses an international dialling prefix of 00. When it is written as
   2290    *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
   2291    *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
   2292    *     specific).
   2293    * @return  true if the number is possible
   2294    */
   2295   public boolean isPossibleNumber(String number, String regionDialingFrom) {
   2296     try {
   2297       return isPossibleNumber(parse(number, regionDialingFrom));
   2298     } catch (NumberParseException e) {
   2299       return false;
   2300     }
   2301   }
   2302 
   2303   /**
   2304    * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
   2305    * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
   2306    * the PhoneNumber object passed in will not be modified.
   2307    * @param number a PhoneNumber object which contains a number that is too long to be valid.
   2308    * @return  true if a valid phone number can be successfully extracted.
   2309    */
   2310   public boolean truncateTooLongNumber(PhoneNumber number) {
   2311     if (isValidNumber(number)) {
   2312       return true;
   2313     }
   2314     PhoneNumber numberCopy = new PhoneNumber();
   2315     numberCopy.mergeFrom(number);
   2316     long nationalNumber = number.getNationalNumber();
   2317     do {
   2318       nationalNumber /= 10;
   2319       numberCopy.setNationalNumber(nationalNumber);
   2320       if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
   2321           nationalNumber == 0) {
   2322         return false;
   2323       }
   2324     } while (!isValidNumber(numberCopy));
   2325     number.setNationalNumber(nationalNumber);
   2326     return true;
   2327   }
   2328 
   2329   /**
   2330    * Gets an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
   2331    *
   2332    * @param regionCode  the region where the phone number is being entered
   2333    * @return  an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
   2334    *     to format phone numbers in the specific region "as you type"
   2335    */
   2336   public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
   2337     return new AsYouTypeFormatter(regionCode);
   2338   }
   2339 
   2340   // Extracts country calling code from fullNumber, returns it and places the remaining number in
   2341   // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
   2342   // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
   2343   // unmodified.
   2344   int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
   2345     if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
   2346       // Country codes do not begin with a '0'.
   2347       return 0;
   2348     }
   2349     int potentialCountryCode;
   2350     int numberLength = fullNumber.length();
   2351     for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
   2352       potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
   2353       if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
   2354         nationalNumber.append(fullNumber.substring(i));
   2355         return potentialCountryCode;
   2356       }
   2357     }
   2358     return 0;
   2359   }
   2360 
   2361   /**
   2362    * Tries to extract a country calling code from a number. This method will return zero if no
   2363    * country calling code is considered to be present. Country calling codes are extracted in the
   2364    * following ways:
   2365    * <ul>
   2366    *  <li> by stripping the international dialing prefix of the region the person is dialing from,
   2367    *       if this is present in the number, and looking at the next digits
   2368    *  <li> by stripping the '+' sign if present and then looking at the next digits
   2369    *  <li> by comparing the start of the number and the country calling code of the default region.
   2370    *       If the number is not considered possible for the numbering plan of the default region
   2371    *       initially, but starts with the country calling code of this region, validation will be
   2372    *       reattempted after stripping this country calling code. If this number is considered a
   2373    *       possible number, then the first digits will be considered the country calling code and
   2374    *       removed as such.
   2375    * </ul>
   2376    * It will throw a NumberParseException if the number starts with a '+' but the country calling
   2377    * code supplied after this does not match that of any known region.
   2378    *
   2379    * @param number  non-normalized telephone number that we wish to extract a country calling
   2380    *     code from - may begin with '+'
   2381    * @param defaultRegionMetadata  metadata about the region this number may be from
   2382    * @param nationalNumber  a string buffer to store the national significant number in, in the case
   2383    *     that a country calling code was extracted. The number is appended to any existing contents.
   2384    *     If no country calling code was extracted, this will be left unchanged.
   2385    * @param keepRawInput  true if the country_code_source and preferred_carrier_code fields of
   2386    *     phoneNumber should be populated.
   2387    * @param phoneNumber  the PhoneNumber object where the country_code and country_code_source need
   2388    *     to be populated. Note the country_code is always populated, whereas country_code_source is
   2389    *     only populated when keepCountryCodeSource is true.
   2390    * @return  the country calling code extracted or 0 if none could be extracted
   2391    */
   2392   // @VisibleForTesting
   2393   int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
   2394                               StringBuilder nationalNumber, boolean keepRawInput,
   2395                               PhoneNumber phoneNumber)
   2396       throws NumberParseException {
   2397     if (number.length() == 0) {
   2398       return 0;
   2399     }
   2400     StringBuilder fullNumber = new StringBuilder(number);
   2401     // Set the default prefix to be something that will never match.
   2402     String possibleCountryIddPrefix = "NonMatch";
   2403     if (defaultRegionMetadata != null) {
   2404       possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
   2405     }
   2406 
   2407     CountryCodeSource countryCodeSource =
   2408         maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
   2409     if (keepRawInput) {
   2410       phoneNumber.setCountryCodeSource(countryCodeSource);
   2411     }
   2412     if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
   2413       if (fullNumber.length() < MIN_LENGTH_FOR_NSN) {
   2414         throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   2415                                        "Phone number had an IDD, but after this was not "
   2416                                        + "long enough to be a viable phone number.");
   2417       }
   2418       int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
   2419       if (potentialCountryCode != 0) {
   2420         phoneNumber.setCountryCode(potentialCountryCode);
   2421         return potentialCountryCode;
   2422       }
   2423 
   2424       // If this fails, they must be using a strange country calling code that we don't recognize,
   2425       // or that doesn't exist.
   2426       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2427                                      "Country calling code supplied was not recognised.");
   2428     } else if (defaultRegionMetadata != null) {
   2429       // Check to see if the number starts with the country calling code for the default region. If
   2430       // so, we remove the country calling code, and do some checks on the validity of the number
   2431       // before and after.
   2432       int defaultCountryCode = defaultRegionMetadata.getCountryCode();
   2433       String defaultCountryCodeString = String.valueOf(defaultCountryCode);
   2434       String normalizedNumber = fullNumber.toString();
   2435       if (normalizedNumber.startsWith(defaultCountryCodeString)) {
   2436         StringBuilder potentialNationalNumber =
   2437             new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
   2438         PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
   2439         Pattern validNumberPattern =
   2440             regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
   2441         maybeStripNationalPrefixAndCarrierCode(
   2442             potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
   2443         Pattern possibleNumberPattern =
   2444             regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
   2445         // If the number was not valid before but is valid now, or if it was too long before, we
   2446         // consider the number with the country calling code stripped to be a better result and
   2447         // keep that instead.
   2448         if ((!validNumberPattern.matcher(fullNumber).matches() &&
   2449              validNumberPattern.matcher(potentialNationalNumber).matches()) ||
   2450              testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
   2451                   == ValidationResult.TOO_LONG) {
   2452           nationalNumber.append(potentialNationalNumber);
   2453           if (keepRawInput) {
   2454             phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
   2455           }
   2456           phoneNumber.setCountryCode(defaultCountryCode);
   2457           return defaultCountryCode;
   2458         }
   2459       }
   2460     }
   2461     // No country calling code present.
   2462     phoneNumber.setCountryCode(0);
   2463     return 0;
   2464   }
   2465 
   2466   /**
   2467    * Strips the IDD from the start of the number if present. Helper function used by
   2468    * maybeStripInternationalPrefixAndNormalize.
   2469    */
   2470   private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
   2471     Matcher m = iddPattern.matcher(number);
   2472     if (m.lookingAt()) {
   2473       int matchEnd = m.end();
   2474       // Only strip this if the first digit after the match is not a 0, since country calling codes
   2475       // cannot begin with 0.
   2476       Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
   2477       if (digitMatcher.find()) {
   2478         String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
   2479         if (normalizedGroup.equals("0")) {
   2480           return false;
   2481         }
   2482       }
   2483       number.delete(0, matchEnd);
   2484       return true;
   2485     }
   2486     return false;
   2487   }
   2488 
   2489   /**
   2490    * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
   2491    * the resulting number, and indicates if an international prefix was present.
   2492    *
   2493    * @param number  the non-normalized telephone number that we wish to strip any international
   2494    *     dialing prefix from.
   2495    * @param possibleIddPrefix  the international direct dialing prefix from the region we
   2496    *     think this number may be dialed in
   2497    * @return  the corresponding CountryCodeSource if an international dialing prefix could be
   2498    *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
   2499    *     not seem to be in international format.
   2500    */
   2501   // @VisibleForTesting
   2502   CountryCodeSource maybeStripInternationalPrefixAndNormalize(
   2503       StringBuilder number,
   2504       String possibleIddPrefix) {
   2505     if (number.length() == 0) {
   2506       return CountryCodeSource.FROM_DEFAULT_COUNTRY;
   2507     }
   2508     // Check to see if the number begins with one or more plus signs.
   2509     Matcher m = PLUS_CHARS_PATTERN.matcher(number);
   2510     if (m.lookingAt()) {
   2511       number.delete(0, m.end());
   2512       // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
   2513       normalize(number);
   2514       return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
   2515     }
   2516     // Attempt to parse the first digits as an international prefix.
   2517     Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
   2518     normalize(number);
   2519     return parsePrefixAsIdd(iddPattern, number)
   2520            ? CountryCodeSource.FROM_NUMBER_WITH_IDD
   2521            : CountryCodeSource.FROM_DEFAULT_COUNTRY;
   2522   }
   2523 
   2524   /**
   2525    * Strips any national prefix (such as 0, 1) present in the number provided.
   2526    *
   2527    * @param number  the normalized telephone number that we wish to strip any national
   2528    *     dialing prefix from
   2529    * @param metadata  the metadata for the region that we think this number is from
   2530    * @param carrierCode  a place to insert the carrier code if one is extracted
   2531    * @return true if a national prefix or carrier code (or both) could be extracted.
   2532    */
   2533   // @VisibleForTesting
   2534   boolean maybeStripNationalPrefixAndCarrierCode(
   2535       StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
   2536     int numberLength = number.length();
   2537     String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
   2538     if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
   2539       // Early return for numbers of zero length.
   2540       return false;
   2541     }
   2542     // Attempt to parse the first digits as a national prefix.
   2543     Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
   2544     if (prefixMatcher.lookingAt()) {
   2545       Pattern nationalNumberRule =
   2546           regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
   2547       // Check if the original number is viable.
   2548       boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
   2549       // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
   2550       // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
   2551       // remove the national prefix.
   2552       int numOfGroups = prefixMatcher.groupCount();
   2553       String transformRule = metadata.getNationalPrefixTransformRule();
   2554       if (transformRule == null || transformRule.length() == 0 ||
   2555           prefixMatcher.group(numOfGroups) == null) {
   2556         // If the original number was viable, and the resultant number is not, we return.
   2557         if (isViableOriginalNumber &&
   2558             !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
   2559           return false;
   2560         }
   2561         if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
   2562           carrierCode.append(prefixMatcher.group(1));
   2563         }
   2564         number.delete(0, prefixMatcher.end());
   2565         return true;
   2566       } else {
   2567         // Check that the resultant number is still viable. If not, return. Check this by copying
   2568         // the string buffer and making the transformation on the copy first.
   2569         StringBuilder transformedNumber = new StringBuilder(number);
   2570         transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
   2571         if (isViableOriginalNumber &&
   2572             !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
   2573           return false;
   2574         }
   2575         if (carrierCode != null && numOfGroups > 1) {
   2576           carrierCode.append(prefixMatcher.group(1));
   2577         }
   2578         number.replace(0, number.length(), transformedNumber.toString());
   2579         return true;
   2580       }
   2581     }
   2582     return false;
   2583   }
   2584 
   2585   /**
   2586    * Strips any extension (as in, the part of the number dialled after the call is connected,
   2587    * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
   2588    *
   2589    * @param number  the non-normalized telephone number that we wish to strip the extension from
   2590    * @return        the phone extension
   2591    */
   2592   // @VisibleForTesting
   2593   String maybeStripExtension(StringBuilder number) {
   2594     Matcher m = EXTN_PATTERN.matcher(number);
   2595     // If we find a potential extension, and the number preceding this is a viable number, we assume
   2596     // it is an extension.
   2597     if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
   2598       // The numbers are captured into groups in the regular expression.
   2599       for (int i = 1, length = m.groupCount(); i <= length; i++) {
   2600         if (m.group(i) != null) {
   2601           // We go through the capturing groups until we find one that captured some digits. If none
   2602           // did, then we will return the empty string.
   2603           String extension = m.group(i);
   2604           number.delete(m.start(), number.length());
   2605           return extension;
   2606         }
   2607       }
   2608     }
   2609     return "";
   2610   }
   2611 
   2612   /**
   2613    * Checks to see that the region code used is valid, or if it is not valid, that the number to
   2614    * parse starts with a + symbol so that we can attempt to infer the region from the number.
   2615    * Returns false if it cannot use the region provided and the region cannot be inferred.
   2616    */
   2617   private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
   2618     if (!isValidRegionCode(defaultRegion)) {
   2619       // If the number is null or empty, we can't infer the region.
   2620       if (numberToParse == null || numberToParse.length() == 0 ||
   2621           !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
   2622         return false;
   2623       }
   2624     }
   2625     return true;
   2626   }
   2627 
   2628   /**
   2629    * Parses a string and returns it in proto buffer format. This method will throw a
   2630    * {@link com.android.i18n.phonenumbers.NumberParseException} if the number is not considered to be
   2631    * a possible number. Note that validation of whether the number is actually a valid number for a
   2632    * particular region is not performed. This can be done separately with {@link #isValidNumber}.
   2633    *
   2634    * @param numberToParse     number that we are attempting to parse. This can contain formatting
   2635    *                          such as +, ( and -, as well as a phone number extension.
   2636    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2637    *                          if the number being parsed is not written in international format.
   2638    *                          The country_code for the number in this case would be stored as that
   2639    *                          of the default region supplied. If the number is guaranteed to
   2640    *                          start with a '+' followed by the country calling code, then
   2641    *                          "ZZ" or null can be supplied.
   2642    * @return                  a phone number proto buffer filled with the parsed number
   2643    * @throws NumberParseException  if the string is not considered to be a viable phone number or if
   2644    *                               no default region was supplied and the number is not in
   2645    *                               international format (does not start with +)
   2646    */
   2647   public PhoneNumber parse(String numberToParse, String defaultRegion)
   2648       throws NumberParseException {
   2649     PhoneNumber phoneNumber = new PhoneNumber();
   2650     parse(numberToParse, defaultRegion, phoneNumber);
   2651     return phoneNumber;
   2652   }
   2653 
   2654   /**
   2655    * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
   2656    * decrease object creation when invoked many times.
   2657    */
   2658   public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
   2659       throws NumberParseException {
   2660     parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
   2661   }
   2662 
   2663   /**
   2664    * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
   2665    * in that it always populates the raw_input field of the protocol buffer with numberToParse as
   2666    * well as the country_code_source field.
   2667    *
   2668    * @param numberToParse     number that we are attempting to parse. This can contain formatting
   2669    *                          such as +, ( and -, as well as a phone number extension.
   2670    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2671    *                          if the number being parsed is not written in international format.
   2672    *                          The country calling code for the number in this case would be stored
   2673    *                          as that of the default region supplied.
   2674    * @return                  a phone number proto buffer filled with the parsed number
   2675    * @throws NumberParseException  if the string is not considered to be a viable phone number or if
   2676    *                               no default region was supplied
   2677    */
   2678   public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
   2679       throws NumberParseException {
   2680     PhoneNumber phoneNumber = new PhoneNumber();
   2681     parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
   2682     return phoneNumber;
   2683   }
   2684 
   2685   /**
   2686    * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
   2687    * a parameter to decrease object creation when invoked many times.
   2688    */
   2689   public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
   2690                                    PhoneNumber phoneNumber)
   2691       throws NumberParseException {
   2692     parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
   2693   }
   2694 
   2695   /**
   2696    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
   2697    * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
   2698    * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
   2699    *
   2700    * @param text              the text to search for phone numbers, null for no text
   2701    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2702    *                          if the number being parsed is not written in international format. The
   2703    *                          country_code for the number in this case would be stored as that of
   2704    *                          the default region supplied. May be null if only international
   2705    *                          numbers are expected.
   2706    */
   2707   public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
   2708     return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
   2709   }
   2710 
   2711   /**
   2712    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
   2713    *
   2714    * @param text              the text to search for phone numbers, null for no text
   2715    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2716    *                          if the number being parsed is not written in international format. The
   2717    *                          country_code for the number in this case would be stored as that of
   2718    *                          the default region supplied. May be null if only international
   2719    *                          numbers are expected.
   2720    * @param leniency          the leniency to use when evaluating candidate phone numbers
   2721    * @param maxTries          the maximum number of invalid numbers to try before giving up on the
   2722    *                          text. This is to cover degenerate cases where the text has a lot of
   2723    *                          false positives in it. Must be {@code >= 0}.
   2724    */
   2725   public Iterable<PhoneNumberMatch> findNumbers(
   2726       final CharSequence text, final String defaultRegion, final Leniency leniency,
   2727       final long maxTries) {
   2728 
   2729     return new Iterable<PhoneNumberMatch>() {
   2730       public Iterator<PhoneNumberMatch> iterator() {
   2731         return new PhoneNumberMatcher(
   2732             PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
   2733       }
   2734     };
   2735   }
   2736 
   2737   /**
   2738    * Parses a string and fills up the phoneNumber. This method is the same as the public
   2739    * parse() method, with the exception that it allows the default region to be null, for use by
   2740    * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
   2741    * to be null or unknown ("ZZ").
   2742    */
   2743   private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
   2744                            boolean checkRegion, PhoneNumber phoneNumber)
   2745       throws NumberParseException {
   2746     if (numberToParse == null) {
   2747       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
   2748                                      "The phone number supplied was null.");
   2749     } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
   2750       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
   2751                                      "The string supplied was too long to parse.");
   2752     }
   2753     // Extract a possible number from the string passed in (this strips leading characters that
   2754     // could not be the start of a phone number.)
   2755     String number = extractPossibleNumber(numberToParse);
   2756     if (!isViablePhoneNumber(number)) {
   2757       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
   2758                                      "The string supplied did not seem to be a phone number.");
   2759     }
   2760 
   2761     // Check the region supplied is valid, or that the extracted number starts with some sort of +
   2762     // sign so the number's region can be determined.
   2763     if (checkRegion && !checkRegionForParsing(number, defaultRegion)) {
   2764       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2765                                      "Missing or invalid default region.");
   2766     }
   2767 
   2768     if (keepRawInput) {
   2769       phoneNumber.setRawInput(numberToParse);
   2770     }
   2771     StringBuilder nationalNumber = new StringBuilder(number);
   2772     // Attempt to parse extension first, since it doesn't require region-specific data and we want
   2773     // to have the non-normalised number here.
   2774     String extension = maybeStripExtension(nationalNumber);
   2775     if (extension.length() > 0) {
   2776       phoneNumber.setExtension(extension);
   2777     }
   2778 
   2779     PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
   2780     // Check to see if the number is given in international format so we know whether this number is
   2781     // from the default region or not.
   2782     StringBuilder normalizedNationalNumber = new StringBuilder();
   2783     int countryCode = 0;
   2784     try {
   2785       // TODO: This method should really just take in the string buffer that has already
   2786       // been created, and just remove the prefix, rather than taking in a string and then
   2787       // outputting a string buffer.
   2788       countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
   2789                                             normalizedNationalNumber, keepRawInput, phoneNumber);
   2790     } catch (NumberParseException e) {
   2791       Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
   2792       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
   2793           matcher.lookingAt()) {
   2794         // Strip the plus-char, and try again.
   2795         countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
   2796                                               regionMetadata, normalizedNationalNumber,
   2797                                               keepRawInput, phoneNumber);
   2798         if (countryCode == 0) {
   2799           throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2800                                          "Could not interpret numbers after plus-sign.");
   2801         }
   2802       } else {
   2803         throw new NumberParseException(e.getErrorType(), e.getMessage());
   2804       }
   2805     }
   2806     if (countryCode != 0) {
   2807       String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
   2808       if (!phoneNumberRegion.equals(defaultRegion)) {
   2809         regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
   2810       }
   2811     } else {
   2812       // If no extracted country calling code, use the region supplied instead. The national number
   2813       // is just the normalized version of the number we were given to parse.
   2814       normalize(nationalNumber);
   2815       normalizedNationalNumber.append(nationalNumber);
   2816       if (defaultRegion != null) {
   2817         countryCode = regionMetadata.getCountryCode();
   2818         phoneNumber.setCountryCode(countryCode);
   2819       } else if (keepRawInput) {
   2820         phoneNumber.clearCountryCodeSource();
   2821       }
   2822     }
   2823     if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
   2824       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
   2825                                      "The string supplied is too short to be a phone number.");
   2826     }
   2827     if (regionMetadata != null) {
   2828       StringBuilder carrierCode = new StringBuilder();
   2829       maybeStripNationalPrefixAndCarrierCode(normalizedNationalNumber, regionMetadata, carrierCode);
   2830       if (keepRawInput) {
   2831         phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
   2832       }
   2833     }
   2834     int lengthOfNationalNumber = normalizedNationalNumber.length();
   2835     if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
   2836       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
   2837                                      "The string supplied is too short to be a phone number.");
   2838     }
   2839     if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
   2840       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
   2841                                      "The string supplied is too long to be a phone number.");
   2842     }
   2843     if (normalizedNationalNumber.charAt(0) == '0') {
   2844       phoneNumber.setItalianLeadingZero(true);
   2845     }
   2846     phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
   2847   }
   2848 
   2849   /**
   2850    * Takes two phone numbers and compares them for equality.
   2851    *
   2852    * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
   2853    * and any extension present are the same.
   2854    * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
   2855    * the same.
   2856    * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
   2857    * the same, and one NSN could be a shorter version of the other number. This includes the case
   2858    * where one has an extension specified, and the other does not.
   2859    * Returns NO_MATCH otherwise.
   2860    * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
   2861    * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
   2862    *
   2863    * @param firstNumberIn  first number to compare
   2864    * @param secondNumberIn  second number to compare
   2865    *
   2866    * @return  NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
   2867    *     of the two numbers, described in the method definition.
   2868    */
   2869   public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
   2870     // Make copies of the phone number so that the numbers passed in are not edited.
   2871     PhoneNumber firstNumber = new PhoneNumber();
   2872     firstNumber.mergeFrom(firstNumberIn);
   2873     PhoneNumber secondNumber = new PhoneNumber();
   2874     secondNumber.mergeFrom(secondNumberIn);
   2875     // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
   2876     // empty-string extensions so that we can use the proto-buffer equality method.
   2877     firstNumber.clearRawInput();
   2878     firstNumber.clearCountryCodeSource();
   2879     firstNumber.clearPreferredDomesticCarrierCode();
   2880     secondNumber.clearRawInput();
   2881     secondNumber.clearCountryCodeSource();
   2882     secondNumber.clearPreferredDomesticCarrierCode();
   2883     if (firstNumber.hasExtension() &&
   2884         firstNumber.getExtension().length() == 0) {
   2885         firstNumber.clearExtension();
   2886     }
   2887     if (secondNumber.hasExtension() &&
   2888         secondNumber.getExtension().length() == 0) {
   2889         secondNumber.clearExtension();
   2890     }
   2891     // Early exit if both had extensions and these are different.
   2892     if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
   2893         !firstNumber.getExtension().equals(secondNumber.getExtension())) {
   2894       return MatchType.NO_MATCH;
   2895     }
   2896     int firstNumberCountryCode = firstNumber.getCountryCode();
   2897     int secondNumberCountryCode = secondNumber.getCountryCode();
   2898     // Both had country_code specified.
   2899     if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
   2900       if (firstNumber.exactlySameAs(secondNumber)) {
   2901         return MatchType.EXACT_MATCH;
   2902       } else if (firstNumberCountryCode == secondNumberCountryCode &&
   2903                  isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
   2904         // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
   2905         // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
   2906         // shorter variant of the other.
   2907         return MatchType.SHORT_NSN_MATCH;
   2908       }
   2909       // This is not a match.
   2910       return MatchType.NO_MATCH;
   2911     }
   2912     // Checks cases where one or both country_code fields were not specified. To make equality
   2913     // checks easier, we first set the country_code fields to be equal.
   2914     firstNumber.setCountryCode(secondNumberCountryCode);
   2915     // If all else was the same, then this is an NSN_MATCH.
   2916     if (firstNumber.exactlySameAs(secondNumber)) {
   2917       return MatchType.NSN_MATCH;
   2918     }
   2919     if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
   2920       return MatchType.SHORT_NSN_MATCH;
   2921     }
   2922     return MatchType.NO_MATCH;
   2923   }
   2924 
   2925   // Returns true when one national number is the suffix of the other or both are the same.
   2926   private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
   2927                                                    PhoneNumber secondNumber) {
   2928     String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
   2929     String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
   2930     // Note that endsWith returns true if the numbers are equal.
   2931     return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
   2932            secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
   2933   }
   2934 
   2935   /**
   2936    * Takes two phone numbers as strings and compares them for equality. This is a convenience
   2937    * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
   2938    *
   2939    * @param firstNumber  first number to compare. Can contain formatting, and can have country
   2940    *     calling code specified with + at the start.
   2941    * @param secondNumber  second number to compare. Can contain formatting, and can have country
   2942    *     calling code specified with + at the start.
   2943    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
   2944    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
   2945    */
   2946   public MatchType isNumberMatch(String firstNumber, String secondNumber) {
   2947     try {
   2948       PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
   2949       return isNumberMatch(firstNumberAsProto, secondNumber);
   2950     } catch (NumberParseException e) {
   2951       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   2952         try {
   2953           PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
   2954           return isNumberMatch(secondNumberAsProto, firstNumber);
   2955         } catch (NumberParseException e2) {
   2956           if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   2957             try {
   2958               PhoneNumber firstNumberProto = new PhoneNumber();
   2959               PhoneNumber secondNumberProto = new PhoneNumber();
   2960               parseHelper(firstNumber, null, false, false, firstNumberProto);
   2961               parseHelper(secondNumber, null, false, false, secondNumberProto);
   2962               return isNumberMatch(firstNumberProto, secondNumberProto);
   2963             } catch (NumberParseException e3) {
   2964               // Fall through and return MatchType.NOT_A_NUMBER.
   2965             }
   2966           }
   2967         }
   2968       }
   2969     }
   2970     // One or more of the phone numbers we are trying to match is not a viable phone number.
   2971     return MatchType.NOT_A_NUMBER;
   2972   }
   2973 
   2974   /**
   2975    * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
   2976    * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
   2977    *
   2978    * @param firstNumber  first number to compare in proto buffer format.
   2979    * @param secondNumber  second number to compare. Can contain formatting, and can have country
   2980    *     calling code specified with + at the start.
   2981    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
   2982    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
   2983    */
   2984   public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
   2985     // First see if the second number has an implicit country calling code, by attempting to parse
   2986     // it.
   2987     try {
   2988       PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
   2989       return isNumberMatch(firstNumber, secondNumberAsProto);
   2990     } catch (NumberParseException e) {
   2991       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   2992         // The second number has no country calling code. EXACT_MATCH is no longer possible.
   2993         // We parse it as if the region was the same as that for the first number, and if
   2994         // EXACT_MATCH is returned, we replace this with NSN_MATCH.
   2995         String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
   2996         try {
   2997           if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
   2998             PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
   2999             MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
   3000             if (match == MatchType.EXACT_MATCH) {
   3001               return MatchType.NSN_MATCH;
   3002             }
   3003             return match;
   3004           } else {
   3005             // If the first number didn't have a valid country calling code, then we parse the
   3006             // second number without one as well.
   3007             PhoneNumber secondNumberProto = new PhoneNumber();
   3008             parseHelper(secondNumber, null, false, false, secondNumberProto);
   3009             return isNumberMatch(firstNumber, secondNumberProto);
   3010           }
   3011         } catch (NumberParseException e2) {
   3012           // Fall-through to return NOT_A_NUMBER.
   3013         }
   3014       }
   3015     }
   3016     // One or more of the phone numbers we are trying to match is not a viable phone number.
   3017     return MatchType.NOT_A_NUMBER;
   3018   }
   3019 
   3020   /**
   3021    * Returns true if the number can be dialled from outside the region, or unknown. If the number
   3022    * can only be dialled from within the region, returns false. Does not check the number is a valid
   3023    * number.
   3024    * TODO: Make this method public when we have enough metadata to make it worthwhile.
   3025    *
   3026    * @param number  the phone-number for which we want to know whether it is diallable from
   3027    *     outside the region
   3028    */
   3029   // @VisibleForTesting
   3030   boolean canBeInternationallyDialled(PhoneNumber number) {
   3031     String regionCode = getRegionCodeForNumber(number);
   3032     if (!isValidRegionCode(regionCode)) {
   3033       // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
   3034       // internationally diallable, and will be caught here.
   3035       return true;
   3036     }
   3037     PhoneMetadata metadata = getMetadataForRegion(regionCode);
   3038     String nationalSignificantNumber = getNationalSignificantNumber(number);
   3039     return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
   3040   }
   3041 }
   3042