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