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