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