• 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) {
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       String rawInput = number.getRawInput();
1283       if (rawInput.length() > 0 || !number.hasCountryCode()) {
1284         return rawInput;
1285       }
1286     }
1287     StringBuilder formattedNumber = new StringBuilder(20);
1288     format(number, numberFormat, formattedNumber);
1289     return formattedNumber.toString();
1290   }
1291 
1292   /**
1293    * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
1294    * a parameter to decrease object creation when invoked many times.
1295    */
1296   public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1297                      StringBuilder formattedNumber) {
1298     // Clear the StringBuilder first.
1299     formattedNumber.setLength(0);
1300     int countryCallingCode = number.getCountryCode();
1301     String nationalSignificantNumber = getNationalSignificantNumber(number);
1302 
1303     if (numberFormat == PhoneNumberFormat.E164) {
1304       // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1305       // of the national number needs to be applied. Extensions are not formatted.
1306       formattedNumber.append(nationalSignificantNumber);
1307       prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1308                                          formattedNumber);
1309       return;
1310     }
1311     if (!hasValidCountryCallingCode(countryCallingCode)) {
1312       formattedNumber.append(nationalSignificantNumber);
1313       return;
1314     }
1315     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1316     // share a country calling code is contained by only one region for performance reasons. For
1317     // example, for NANPA regions it will be contained in the metadata for US.
1318     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1319     // Metadata cannot be null because the country calling code is valid (which means that the
1320     // region code cannot be ZZ and must be one of our supported region codes).
1321     PhoneMetadata metadata =
1322         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1323     formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1324     maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1325     prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1326   }
1327 
1328   /**
1329    * Formats a phone number in the specified format using client-defined formatting rules. Note that
1330    * if the phone number has a country calling code of zero or an otherwise invalid country calling
1331    * code, we cannot work out things like whether there should be a national prefix applied, or how
1332    * to format extensions, so we return the national significant number with no formatting applied.
1333    *
1334    * @param number  the phone number to be formatted
1335    * @param numberFormat  the format the phone number should be formatted into
1336    * @param userDefinedFormats  formatting rules specified by clients
1337    * @return  the formatted phone number
1338    */
1339   public String formatByPattern(PhoneNumber number,
1340                                 PhoneNumberFormat numberFormat,
1341                                 List<NumberFormat> userDefinedFormats) {
1342     int countryCallingCode = number.getCountryCode();
1343     String nationalSignificantNumber = getNationalSignificantNumber(number);
1344     if (!hasValidCountryCallingCode(countryCallingCode)) {
1345       return nationalSignificantNumber;
1346     }
1347     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1348     // share a country calling code is contained by only one region for performance reasons. For
1349     // example, for NANPA regions it will be contained in the metadata for US.
1350     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1351     // Metadata cannot be null because the country calling code is valid.
1352     PhoneMetadata metadata =
1353         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1354 
1355     StringBuilder formattedNumber = new StringBuilder(20);
1356 
1357     NumberFormat formattingPattern =
1358         chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1359     if (formattingPattern == null) {
1360       // If no pattern above is matched, we format the number as a whole.
1361       formattedNumber.append(nationalSignificantNumber);
1362     } else {
1363       NumberFormat.Builder numFormatCopy = NumberFormat.newBuilder();
1364       // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1365       // need to copy the rule so that subsequent replacements for different numbers have the
1366       // appropriate national prefix.
1367       numFormatCopy.mergeFrom(formattingPattern);
1368       String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1369       if (nationalPrefixFormattingRule.length() > 0) {
1370         String nationalPrefix = metadata.getNationalPrefix();
1371         if (nationalPrefix.length() > 0) {
1372           // Replace $NP with national prefix and $FG with the first group ($1).
1373           nationalPrefixFormattingRule =
1374               nationalPrefixFormattingRule.replace(NP_STRING, nationalPrefix);
1375           nationalPrefixFormattingRule = nationalPrefixFormattingRule.replace(FG_STRING, "$1");
1376           numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1377         } else {
1378           // We don't want to have a rule for how to format the national prefix if there isn't one.
1379           numFormatCopy.clearNationalPrefixFormattingRule();
1380         }
1381       }
1382       formattedNumber.append(
1383           formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy.build(), numberFormat));
1384     }
1385     maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1386     prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1387     return formattedNumber.toString();
1388   }
1389 
1390   /**
1391    * Formats a phone number in national format for dialing using the carrier as specified in the
1392    * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1393    * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1394    * contains an empty string, returns the number in national format without any carrier code.
1395    *
1396    * @param number  the phone number to be formatted
1397    * @param carrierCode  the carrier selection code to be used
1398    * @return  the formatted phone number in national format for dialing using the carrier as
1399    *     specified in the {@code carrierCode}
1400    */
1401   public String formatNationalNumberWithCarrierCode(PhoneNumber number, CharSequence carrierCode) {
1402     int countryCallingCode = number.getCountryCode();
1403     String nationalSignificantNumber = getNationalSignificantNumber(number);
1404     if (!hasValidCountryCallingCode(countryCallingCode)) {
1405       return nationalSignificantNumber;
1406     }
1407 
1408     // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1409     // share a country calling code is contained by only one region for performance reasons. For
1410     // example, for NANPA regions it will be contained in the metadata for US.
1411     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1412     // Metadata cannot be null because the country calling code is valid.
1413     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1414 
1415     StringBuilder formattedNumber = new StringBuilder(20);
1416     formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1417                                      PhoneNumberFormat.NATIONAL, carrierCode));
1418     maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1419     prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1420                                        formattedNumber);
1421     return formattedNumber.toString();
1422   }
1423 
1424   private PhoneMetadata getMetadataForRegionOrCallingCode(
1425       int countryCallingCode, String regionCode) {
1426     return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1427         ? getMetadataForNonGeographicalRegion(countryCallingCode)
1428         : getMetadataForRegion(regionCode);
1429   }
1430 
1431   /**
1432    * Formats a phone number in national format for dialing using the carrier as specified in the
1433    * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1434    * use the {@code fallbackCarrierCode} passed in instead. If there is no
1435    * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1436    * string, return the number in national format without any carrier code.
1437    *
1438    * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1439    * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
1440    *
1441    * @param number  the phone number to be formatted
1442    * @param fallbackCarrierCode  the carrier selection code to be used, if none is found in the
1443    *     phone number itself
1444    * @return  the formatted phone number in national format for dialing using the number's
1445    *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1446    *     none is found
1447    */
1448   public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
1449                                                              CharSequence fallbackCarrierCode) {
1450     return formatNationalNumberWithCarrierCode(number,
1451         // Historically, we set this to an empty string when parsing with raw input if none was
1452         // found in the input string. However, this doesn't result in a number we can dial. For this
1453         // reason, we treat the empty string the same as if it isn't set at all.
1454         number.getPreferredDomesticCarrierCode().length() > 0
1455         ? number.getPreferredDomesticCarrierCode()
1456         : fallbackCarrierCode);
1457   }
1458 
1459   /**
1460    * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1461    * specific region. If the number cannot be reached from the region (e.g. some countries block
1462    * toll-free numbers from being called outside of the country), the method returns an empty
1463    * string.
1464    *
1465    * @param number  the phone number to be formatted
1466    * @param regionCallingFrom  the region where the call is being placed
1467    * @param withFormatting  whether the number should be returned with formatting symbols, such as
1468    *     spaces and dashes.
1469    * @return  the formatted phone number
1470    */
1471   public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1472                                              boolean withFormatting) {
1473     int countryCallingCode = number.getCountryCode();
1474     if (!hasValidCountryCallingCode(countryCallingCode)) {
1475       return number.hasRawInput() ? number.getRawInput() : "";
1476     }
1477 
1478     String formattedNumber = "";
1479     // Clear the extension, as that part cannot normally be dialed together with the main number.
1480     PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1481     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1482     PhoneNumberType numberType = getNumberType(numberNoExt);
1483     boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN);
1484     if (regionCallingFrom.equals(regionCode)) {
1485       boolean isFixedLineOrMobile =
1486           (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE)
1487           || (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1488       // Carrier codes may be needed in some countries. We handle this here.
1489       if (regionCode.equals("BR") && isFixedLineOrMobile) {
1490         // Historically, we set this to an empty string when parsing with raw input if none was
1491         // found in the input string. However, this doesn't result in a number we can dial. For this
1492         // reason, we treat the empty string the same as if it isn't set at all.
1493         formattedNumber = numberNoExt.getPreferredDomesticCarrierCode().length() > 0
1494             ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1495             // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1496             // called within Brazil. Without that, most of the carriers won't connect the call.
1497             // Because of that, we return an empty string here.
1498             : "";
1499       } else if (countryCallingCode == NANPA_COUNTRY_CODE) {
1500         // For NANPA countries, we output international format for numbers that can be dialed
1501         // internationally, since that always works, except for numbers which might potentially be
1502         // short numbers, which are always dialled in national format.
1503         PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom);
1504         if (canBeInternationallyDialled(numberNoExt)
1505             && testNumberLength(getNationalSignificantNumber(numberNoExt), regionMetadata)
1506                 != ValidationResult.TOO_SHORT) {
1507           formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1508         } else {
1509           formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1510         }
1511       } else {
1512         // For non-geographical countries, and Mexican, Chilean, and Uzbek fixed line and mobile
1513         // numbers, we output international format for numbers that can be dialed internationally as
1514         // that always works.
1515         if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY)
1516              // MX fixed line and mobile numbers should always be formatted in international format,
1517              // even when dialed within MX. For national format to work, a carrier code needs to be
1518              // used, and the correct carrier code depends on if the caller and callee are from the
1519              // same local area. It is trickier to get that to work correctly than using
1520              // international format, which is tested to work fine on all carriers.
1521              // CL fixed line numbers need the national prefix when dialing in the national format,
1522              // but don't have it when used for display. The reverse is true for mobile numbers.  As
1523              // a result, we output them in the international format to make it work.
1524              // UZ mobile and fixed-line numbers have to be formatted in international format or
1525              // prefixed with special codes like 03, 04 (for fixed-line) and 05 (for mobile) for
1526              // dialling successfully from mobile devices. As we do not have complete information on
1527              // special codes and to be consistent with formatting across all phone types we return
1528              // the number in international format here.
1529              || ((regionCode.equals("MX") || regionCode.equals("CL")
1530                  || regionCode.equals("UZ")) && isFixedLineOrMobile))
1531             && canBeInternationallyDialled(numberNoExt)) {
1532           formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1533         } else {
1534           formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1535         }
1536       }
1537     } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) {
1538       // We assume that short numbers are not diallable from outside their region, so if a number
1539       // is not a valid regular length phone number, we treat it as if it cannot be internationally
1540       // dialled.
1541       return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1542                             : format(numberNoExt, PhoneNumberFormat.E164);
1543     }
1544     return withFormatting ? formattedNumber
1545                           : normalizeDiallableCharsOnly(formattedNumber);
1546   }
1547 
1548   /**
1549    * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1550    * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1551    * same as that of the region where the number is from, then NATIONAL formatting will be applied.
1552    *
1553    * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1554    * calling code, then we return the number with no formatting applied.
1555    *
1556    * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1557    * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1558    * is used. For regions which have multiple international prefixes, the number in its
1559    * INTERNATIONAL format will be returned instead.
1560    *
1561    * @param number  the phone number to be formatted
1562    * @param regionCallingFrom  the region where the call is being placed
1563    * @return  the formatted phone number
1564    */
1565   public String formatOutOfCountryCallingNumber(PhoneNumber number,
1566                                                 String regionCallingFrom) {
1567     if (!isValidRegionCode(regionCallingFrom)) {
1568       logger.log(Level.WARNING,
1569                  "Trying to format number from invalid region "
1570                  + regionCallingFrom
1571                  + ". International formatting applied.");
1572       return format(number, PhoneNumberFormat.INTERNATIONAL);
1573     }
1574     int countryCallingCode = number.getCountryCode();
1575     String nationalSignificantNumber = getNationalSignificantNumber(number);
1576     if (!hasValidCountryCallingCode(countryCallingCode)) {
1577       return nationalSignificantNumber;
1578     }
1579     if (countryCallingCode == NANPA_COUNTRY_CODE) {
1580       if (isNANPACountry(regionCallingFrom)) {
1581         // For NANPA regions, return the national format for these regions but prefix it with the
1582         // country calling code.
1583         return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
1584       }
1585     } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1586       // If regions share a country calling code, the country calling code need not be dialled.
1587       // This also applies when dialling within a region, so this if clause covers both these cases.
1588       // Technically this is the case for dialling from La Reunion to other overseas departments of
1589       // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
1590       // edge case for now and for those cases return the version including country calling code.
1591       // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
1592       return format(number, PhoneNumberFormat.NATIONAL);
1593     }
1594     // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1595     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1596     String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1597 
1598     // In general, if there is a preferred international prefix, use that. Otherwise, for regions
1599     // that have multiple international prefixes, the international format of the number is
1600     // returned since we would not know which one to use.
1601     String internationalPrefixForFormatting = "";
1602     if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1603       internationalPrefixForFormatting =
1604           metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1605     } else if (SINGLE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
1606       internationalPrefixForFormatting = internationalPrefix;
1607     }
1608 
1609     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1610     // Metadata cannot be null because the country calling code is valid.
1611     PhoneMetadata metadataForRegion =
1612         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1613     String formattedNationalNumber =
1614         formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1615     StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1616     maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1617                                   formattedNumber);
1618     if (internationalPrefixForFormatting.length() > 0) {
1619       formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1620           .insert(0, internationalPrefixForFormatting);
1621     } else {
1622       prefixNumberWithCountryCallingCode(countryCallingCode,
1623                                          PhoneNumberFormat.INTERNATIONAL,
1624                                          formattedNumber);
1625     }
1626     return formattedNumber.toString();
1627   }
1628 
1629   /**
1630    * Formats a phone number using the original phone number format (e.g. INTERNATIONAL or NATIONAL)
1631    * that the number is parsed from, provided that the number has been parsed with {@link
1632    * parseAndKeepRawInput}. Otherwise the number will be formatted in NATIONAL format.
1633    *
1634    * <p>The original format is embedded in the country_code_source field of the PhoneNumber object
1635    * passed in, which is only set when parsing keeps the raw input. When we don't have a formatting
1636    * pattern for the number, the method falls back to returning the raw input.
1637    *
1638    * <p>Note this method guarantees no digit will be inserted, removed or modified as a result of
1639    * formatting.
1640    *
1641    * @param number the phone number that needs to be formatted in its original number format
1642    * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number has
1643    *     one
1644    * @return the formatted phone number in its original number format
1645    */
1646   public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
1647     if (number.hasRawInput() && !hasFormattingPatternForNumber(number)) {
1648       // We check if we have the formatting pattern because without that, we might format the number
1649       // as a group without national prefix.
1650       return number.getRawInput();
1651     }
1652     if (!number.hasCountryCodeSource()) {
1653       return format(number, PhoneNumberFormat.NATIONAL);
1654     }
1655     String formattedNumber;
1656     switch (number.getCountryCodeSource()) {
1657       case FROM_NUMBER_WITH_PLUS_SIGN:
1658         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1659         break;
1660       case FROM_NUMBER_WITH_IDD:
1661         formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1662         break;
1663       case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1664         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1665         break;
1666       case FROM_DEFAULT_COUNTRY:
1667         // Fall-through to default case.
1668       default:
1669         String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1670         // We strip non-digits from the NDD here, and from the raw input later, so that we can
1671         // compare them easily.
1672         String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1673         String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1674         if (nationalPrefix == null || nationalPrefix.length() == 0) {
1675           // If the region doesn't have a national prefix at all, we can safely return the national
1676           // format without worrying about a national prefix being added.
1677           formattedNumber = nationalFormat;
1678           break;
1679         }
1680         // Otherwise, we check if the original number was entered with a national prefix.
1681         if (rawInputContainsNationalPrefix(
1682             number.getRawInput(), nationalPrefix, regionCode)) {
1683           // If so, we can safely return the national format.
1684           formattedNumber = nationalFormat;
1685           break;
1686         }
1687         // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1688         // there is no metadata for the region.
1689         PhoneMetadata metadata = getMetadataForRegion(regionCode);
1690         String nationalNumber = getNationalSignificantNumber(number);
1691         NumberFormat formatRule =
1692             chooseFormattingPatternForNumber(metadata.getNumberFormatList(), nationalNumber);
1693         // The format rule could still be null here if the national number was 0 and there was no
1694         // raw input (this should not be possible for numbers generated by the phonenumber library
1695         // as they would also not have a country calling code and we would have exited earlier).
1696         if (formatRule == null) {
1697           formattedNumber = nationalFormat;
1698           break;
1699         }
1700         // When the format we apply to this number doesn't contain national prefix, we can just
1701         // return the national format.
1702         // TODO: Refactor the code below with the code in
1703         // isNationalPrefixPresentIfRequired.
1704         String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1705         // We assume that the first-group symbol will never be _before_ the national prefix.
1706         int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1707         if (indexOfFirstGroup <= 0) {
1708           formattedNumber = nationalFormat;
1709           break;
1710         }
1711         candidateNationalPrefixRule =
1712             candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1713         candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1714         if (candidateNationalPrefixRule.length() == 0) {
1715           // National prefix not used when formatting this number.
1716           formattedNumber = nationalFormat;
1717           break;
1718         }
1719         // Otherwise, we need to remove the national prefix from our output.
1720         NumberFormat.Builder numFormatCopy =  NumberFormat.newBuilder();
1721         numFormatCopy.mergeFrom(formatRule);
1722         numFormatCopy.clearNationalPrefixFormattingRule();
1723         List<NumberFormat> numberFormats = new ArrayList<>(1);
1724         numberFormats.add(numFormatCopy.build());
1725         formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1726         break;
1727     }
1728     String rawInput = number.getRawInput();
1729     // If no digit is inserted/removed/modified as a result of our formatting, we return the
1730     // formatted phone number; otherwise we return the raw input the user entered.
1731     if (formattedNumber != null && rawInput.length() > 0) {
1732       String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1733       String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1734       if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1735         formattedNumber = rawInput;
1736       }
1737     }
1738     return formattedNumber;
1739   }
1740 
1741   // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1742   // national prefix is assumed to be in digits-only form.
1743   private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1744       String regionCode) {
1745     String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1746     if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1747       try {
1748         // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1749         // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1750         // check the validity of the number if the assumed national prefix is removed (777123 won't
1751         // be valid in Japan).
1752         return isValidNumber(
1753             parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1754       } catch (NumberParseException e) {
1755         return false;
1756       }
1757     }
1758     return false;
1759   }
1760 
1761   private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1762     int countryCallingCode = number.getCountryCode();
1763     String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1764     PhoneMetadata metadata =
1765         getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
1766     if (metadata == null) {
1767       return false;
1768     }
1769     String nationalNumber = getNationalSignificantNumber(number);
1770     NumberFormat formatRule =
1771         chooseFormattingPatternForNumber(metadata.getNumberFormatList(), nationalNumber);
1772     return formatRule != null;
1773   }
1774 
1775   /**
1776    * Formats a phone number for out-of-country dialing purposes.
1777    *
1778    * Note that in this version, if the number was entered originally using alpha characters and
1779    * this version of the number is stored in raw_input, this representation of the number will be
1780    * used rather than the digit representation. Grouping information, as specified by characters
1781    * such as "-" and " ", will be retained.
1782    *
1783    * <p><b>Caveats:</b></p>
1784    * <ul>
1785    *  <li> This will not produce good results if the country calling code is both present in the raw
1786    *       input _and_ is the start of the national number. This is not a problem in the regions
1787    *       which typically use alpha numbers.
1788    *  <li> This will also not produce good results if the raw input has any grouping information
1789    *       within the first three digits of the national number, and if the function needs to strip
1790    *       preceding digits/words in the raw input before these digits. Normally people group the
1791    *       first three digits together so this is not a huge problem - and will be fixed if it
1792    *       proves to be so.
1793    * </ul>
1794    *
1795    * @param number  the phone number that needs to be formatted
1796    * @param regionCallingFrom  the region where the call is being placed
1797    * @return  the formatted phone number
1798    */
1799   public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1800                                                     String regionCallingFrom) {
1801     String rawInput = number.getRawInput();
1802     // If there is no raw input, then we can't keep alpha characters because there aren't any.
1803     // In this case, we return formatOutOfCountryCallingNumber.
1804     if (rawInput.length() == 0) {
1805       return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1806     }
1807     int countryCode = number.getCountryCode();
1808     if (!hasValidCountryCallingCode(countryCode)) {
1809       return rawInput;
1810     }
1811     // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1812     // the number in raw_input with the parsed number.
1813     // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1814     // only.
1815     rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1816     // Now we trim everything before the first three digits in the parsed number. We choose three
1817     // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1818     // trim anything at all. Similarly, if the national number was less than three digits, we don't
1819     // trim anything at all.
1820     String nationalNumber = getNationalSignificantNumber(number);
1821     if (nationalNumber.length() > 3) {
1822       int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1823       if (firstNationalNumberDigit != -1) {
1824         rawInput = rawInput.substring(firstNationalNumberDigit);
1825       }
1826     }
1827     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1828     if (countryCode == NANPA_COUNTRY_CODE) {
1829       if (isNANPACountry(regionCallingFrom)) {
1830         return countryCode + " " + rawInput;
1831       }
1832     } else if (metadataForRegionCallingFrom != null
1833         && countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1834       NumberFormat formattingPattern =
1835           chooseFormattingPatternForNumber(metadataForRegionCallingFrom.getNumberFormatList(),
1836                                            nationalNumber);
1837       if (formattingPattern == null) {
1838         // If no pattern above is matched, we format the original input.
1839         return rawInput;
1840       }
1841       NumberFormat.Builder newFormat = NumberFormat.newBuilder();
1842       newFormat.mergeFrom(formattingPattern);
1843       // The first group is the first group of digits that the user wrote together.
1844       newFormat.setPattern("(\\d+)(.*)");
1845       // Here we just concatenate them back together after the national prefix has been fixed.
1846       newFormat.setFormat("$1$2");
1847       // Now we format using this pattern instead of the default pattern, but with the national
1848       // prefix prefixed if necessary.
1849       // This will not work in the cases where the pattern (and not the leading digits) decide
1850       // whether a national prefix needs to be used, since we have overridden the pattern to match
1851       // anything, but that is not the case in the metadata to date.
1852       return formatNsnUsingPattern(rawInput, newFormat.build(), PhoneNumberFormat.NATIONAL);
1853     }
1854     String internationalPrefixForFormatting = "";
1855     // If an unsupported region-calling-from is entered, or a country with multiple international
1856     // prefixes, the international format of the number is returned, unless there is a preferred
1857     // international prefix.
1858     if (metadataForRegionCallingFrom != null) {
1859       String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1860       internationalPrefixForFormatting =
1861           SINGLE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1862           ? internationalPrefix
1863           : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1864     }
1865     StringBuilder formattedNumber = new StringBuilder(rawInput);
1866     String regionCode = getRegionCodeForCountryCode(countryCode);
1867     // Metadata cannot be null because the country calling code is valid.
1868     PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1869     maybeAppendFormattedExtension(number, metadataForRegion,
1870                                   PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1871     if (internationalPrefixForFormatting.length() > 0) {
1872       formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1873           .insert(0, internationalPrefixForFormatting);
1874     } else {
1875       // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1876       // region chosen has multiple international dialling prefixes.
1877       if (!isValidRegionCode(regionCallingFrom)) {
1878         logger.log(Level.WARNING,
1879                    "Trying to format number from invalid region "
1880                    + regionCallingFrom
1881                    + ". International formatting applied.");
1882       }
1883       prefixNumberWithCountryCallingCode(countryCode,
1884                                          PhoneNumberFormat.INTERNATIONAL,
1885                                          formattedNumber);
1886     }
1887     return formattedNumber.toString();
1888   }
1889 
1890   /**
1891    * Gets the national significant number of a phone number. Note a national significant number
1892    * doesn't contain a national prefix or any formatting.
1893    *
1894    * @param number  the phone number for which the national significant number is needed
1895    * @return  the national significant number of the PhoneNumber object passed in
1896    */
1897   public String getNationalSignificantNumber(PhoneNumber number) {
1898     // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
1899     StringBuilder nationalNumber = new StringBuilder();
1900     if (number.isItalianLeadingZero() && number.getNumberOfLeadingZeros() > 0) {
1901       char[] zeros = new char[number.getNumberOfLeadingZeros()];
1902       Arrays.fill(zeros, '0');
1903       nationalNumber.append(new String(zeros));
1904     }
1905     nationalNumber.append(number.getNationalNumber());
1906     return nationalNumber.toString();
1907   }
1908 
1909   /**
1910    * A helper function that is used by format and formatByPattern.
1911    */
1912   private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1913                                                   PhoneNumberFormat numberFormat,
1914                                                   StringBuilder formattedNumber) {
1915     switch (numberFormat) {
1916       case E164:
1917         formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1918         return;
1919       case INTERNATIONAL:
1920         formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1921         return;
1922       case RFC3966:
1923         formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1924             .insert(0, RFC3966_PREFIX);
1925         return;
1926       case NATIONAL:
1927       default:
1928         return;
1929     }
1930   }
1931 
1932   // Simple wrapper of formatNsn for the common case of no carrier code.
1933   private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1934     return formatNsn(number, metadata, numberFormat, null);
1935   }
1936 
1937   // Note in some regions, the national number can be written in two completely different ways
1938   // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1939   // numberFormat parameter here is used to specify which format to use for those cases. If a
1940   // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1941   private String formatNsn(String number,
1942                            PhoneMetadata metadata,
1943                            PhoneNumberFormat numberFormat,
1944                            CharSequence carrierCode) {
1945     List<NumberFormat> intlNumberFormats = metadata.getIntlNumberFormatList();
1946     // When the intlNumberFormats exists, we use that to format national number for the
1947     // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1948     List<NumberFormat> availableFormats =
1949         (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
1950         ? metadata.getNumberFormatList()
1951         : metadata.getIntlNumberFormatList();
1952     NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1953     return (formattingPattern == null)
1954         ? number
1955         : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
1956   }
1957 
1958   NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1959                                                 String nationalNumber) {
1960     for (NumberFormat numFormat : availableFormats) {
1961       int size = numFormat.getLeadingDigitsPatternCount();
1962       if (size == 0 || regexCache.getPatternForRegex(
1963               // We always use the last leading_digits_pattern, as it is the most detailed.
1964               numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
1965         Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1966         if (m.matches()) {
1967           return numFormat;
1968         }
1969       }
1970     }
1971     return null;
1972   }
1973 
1974   // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1975   String formatNsnUsingPattern(String nationalNumber,
1976                                NumberFormat formattingPattern,
1977                                PhoneNumberFormat numberFormat) {
1978     return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
1979   }
1980 
1981   // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1982   // will take place.
1983   private String formatNsnUsingPattern(String nationalNumber,
1984                                        NumberFormat formattingPattern,
1985                                        PhoneNumberFormat numberFormat,
1986                                        CharSequence carrierCode) {
1987     String numberFormatRule = formattingPattern.getFormat();
1988     Matcher m =
1989         regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1990     String formattedNationalNumber = "";
1991     if (numberFormat == PhoneNumberFormat.NATIONAL
1992         && carrierCode != null && carrierCode.length() > 0
1993         && formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1994       // Replace the $CC in the formatting rule with the desired carrier code.
1995       String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1996       carrierCodeFormattingRule = carrierCodeFormattingRule.replace(CC_STRING, carrierCode);
1997       // Now replace the $FG in the formatting rule with the first group and the carrier code
1998       // combined in the appropriate way.
1999       numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
2000           .replaceFirst(carrierCodeFormattingRule);
2001       formattedNationalNumber = m.replaceAll(numberFormatRule);
2002     } else {
2003       // Use the national prefix formatting rule instead.
2004       String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
2005       if (numberFormat == PhoneNumberFormat.NATIONAL
2006           && nationalPrefixFormattingRule != null
2007           && nationalPrefixFormattingRule.length() > 0) {
2008         Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
2009         formattedNationalNumber =
2010             m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
2011       } else {
2012         formattedNationalNumber = m.replaceAll(numberFormatRule);
2013       }
2014     }
2015     if (numberFormat == PhoneNumberFormat.RFC3966) {
2016       // Strip any leading punctuation.
2017       Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
2018       if (matcher.lookingAt()) {
2019         formattedNationalNumber = matcher.replaceFirst("");
2020       }
2021       // Replace the rest with a dash between each number group.
2022       formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
2023     }
2024     return formattedNationalNumber;
2025   }
2026 
2027   /**
2028    * Gets a valid number for the specified region.
2029    *
2030    * @param regionCode  the region for which an example number is needed
2031    * @return  a valid fixed-line number for the specified region. Returns null when the metadata
2032    *    does not contain such information, or the region 001 is passed in. For 001 (representing
2033    *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
2034    */
2035   public PhoneNumber getExampleNumber(String regionCode) {
2036     return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
2037   }
2038 
2039   /**
2040    * Gets an invalid number for the specified region. This is useful for unit-testing purposes,
2041    * where you want to test what will happen with an invalid number. Note that the number that is
2042    * returned will always be able to be parsed and will have the correct country code. It may also
2043    * be a valid *short* number/code for this region. Validity checking such numbers is handled with
2044    * {@link com.google.i18n.phonenumbers.ShortNumberInfo}.
2045    *
2046    * @param regionCode  the region for which an example number is needed
2047    * @return  an invalid number for the specified region. Returns null when an unsupported region or
2048    *     the region 001 (Earth) is passed in.
2049    */
2050   public PhoneNumber getInvalidExampleNumber(String regionCode) {
2051     if (!isValidRegionCode(regionCode)) {
2052       logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
2053       return null;
2054     }
2055     // We start off with a valid fixed-line number since every country supports this. Alternatively
2056     // we could start with a different number type, since fixed-line numbers typically have a wide
2057     // breadth of valid number lengths and we may have to make it very short before we get an
2058     // invalid number.
2059     PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode),
2060         PhoneNumberType.FIXED_LINE);
2061     if (!desc.hasExampleNumber()) {
2062       // This shouldn't happen; we have a test for this.
2063       return null;
2064     }
2065     String exampleNumber = desc.getExampleNumber();
2066     // Try and make the number invalid. We do this by changing the length. We try reducing the
2067     // length of the number, since currently no region has a number that is the same length as
2068     // MIN_LENGTH_FOR_NSN. This is probably quicker than making the number longer, which is another
2069     // alternative. We could also use the possible number pattern to extract the possible lengths of
2070     // the number to make this faster, but this method is only for unit-testing so simplicity is
2071     // preferred to performance.  We don't want to return a number that can't be parsed, so we check
2072     // the number is long enough. We try all possible lengths because phone number plans often have
2073     // overlapping prefixes so the number 123456 might be valid as a fixed-line number, and 12345 as
2074     // a mobile number. It would be faster to loop in a different order, but we prefer numbers that
2075     // look closer to real numbers (and it gives us a variety of different lengths for the resulting
2076     // phone numbers - otherwise they would all be MIN_LENGTH_FOR_NSN digits long.)
2077     for (int phoneNumberLength = exampleNumber.length() - 1;
2078          phoneNumberLength >= MIN_LENGTH_FOR_NSN;
2079          phoneNumberLength--) {
2080       String numberToTry = exampleNumber.substring(0, phoneNumberLength);
2081       try {
2082         PhoneNumber possiblyValidNumber = parse(numberToTry, regionCode);
2083         if (!isValidNumber(possiblyValidNumber)) {
2084           return possiblyValidNumber;
2085         }
2086       } catch (NumberParseException e) {
2087         // Shouldn't happen: we have already checked the length, we know example numbers have
2088         // only valid digits, and we know the region code is fine.
2089       }
2090     }
2091     // We have a test to check that this doesn't happen for any of our supported regions.
2092     return null;
2093   }
2094 
2095   /**
2096    * Gets a valid number for the specified region and number type.
2097    *
2098    * @param regionCode  the region for which an example number is needed
2099    * @param type  the type of number that is needed
2100    * @return  a valid number for the specified region and type. Returns null when the metadata
2101    *     does not contain such information or if an invalid region or region 001 was entered.
2102    *     For 001 (representing non-geographical numbers), call
2103    *     {@link #getExampleNumberForNonGeoEntity} instead.
2104    */
2105   public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
2106     // Check the region code is valid.
2107     if (!isValidRegionCode(regionCode)) {
2108       logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
2109       return null;
2110     }
2111     PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
2112     try {
2113       if (desc.hasExampleNumber()) {
2114         return parse(desc.getExampleNumber(), regionCode);
2115       }
2116     } catch (NumberParseException e) {
2117       logger.log(Level.SEVERE, e.toString());
2118     }
2119     return null;
2120   }
2121 
2122   /**
2123    * Gets a valid number for the specified number type (it may belong to any country).
2124    *
2125    * @param type  the type of number that is needed
2126    * @return  a valid number for the specified type. Returns null when the metadata
2127    *     does not contain such information. This should only happen when no numbers of this type are
2128    *     allocated anywhere in the world anymore.
2129    */
2130   public PhoneNumber getExampleNumberForType(PhoneNumberType type) {
2131     for (String regionCode : getSupportedRegions()) {
2132       PhoneNumber exampleNumber = getExampleNumberForType(regionCode, type);
2133       if (exampleNumber != null) {
2134         return exampleNumber;
2135       }
2136     }
2137     // If there wasn't an example number for a region, try the non-geographical entities.
2138     for (int countryCallingCode : getSupportedGlobalNetworkCallingCodes()) {
2139       PhoneNumberDesc desc = getNumberDescByType(
2140           getMetadataForNonGeographicalRegion(countryCallingCode), type);
2141       try {
2142         if (desc.hasExampleNumber()) {
2143           return parse("+" + countryCallingCode + desc.getExampleNumber(), UNKNOWN_REGION);
2144         }
2145       } catch (NumberParseException e) {
2146         logger.log(Level.SEVERE, e.toString());
2147       }
2148     }
2149     // There are no example numbers of this type for any country in the library.
2150     return null;
2151   }
2152 
2153   /**
2154    * Gets a valid number for the specified country calling code for a non-geographical entity.
2155    *
2156    * @param countryCallingCode  the country calling code for a non-geographical entity
2157    * @return  a valid number for the non-geographical entity. Returns null when the metadata
2158    *    does not contain such information, or the country calling code passed in does not belong
2159    *    to a non-geographical entity.
2160    */
2161   public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
2162     PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
2163     if (metadata != null) {
2164       // For geographical entities, fixed-line data is always present. However, for non-geographical
2165       // entities, this is not the case, so we have to go through different types to find the
2166       // example number. We don't check fixed-line or personal number since they aren't used by
2167       // non-geographical entities (if this changes, a unit-test will catch this.)
2168       for (PhoneNumberDesc desc : Arrays.asList(metadata.getMobile(), metadata.getTollFree(),
2169                metadata.getSharedCost(), metadata.getVoip(), metadata.getVoicemail(),
2170                metadata.getUan(), metadata.getPremiumRate())) {
2171         try {
2172           if (desc != null && desc.hasExampleNumber()) {
2173             return parse("+" + countryCallingCode + desc.getExampleNumber(), UNKNOWN_REGION);
2174           }
2175         } catch (NumberParseException e) {
2176           logger.log(Level.SEVERE, e.toString());
2177         }
2178       }
2179     } else {
2180       logger.log(Level.WARNING,
2181                  "Invalid or unknown country calling code provided: " + countryCallingCode);
2182     }
2183     return null;
2184   }
2185 
2186   /**
2187    * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
2188    * an extension specified.
2189    */
2190   private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
2191                                              PhoneNumberFormat numberFormat,
2192                                              StringBuilder formattedNumber) {
2193     if (number.hasExtension() && number.getExtension().length() > 0) {
2194       if (numberFormat == PhoneNumberFormat.RFC3966) {
2195         formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
2196       } else {
2197         if (metadata.hasPreferredExtnPrefix()) {
2198           formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
2199         } else {
2200           formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
2201         }
2202       }
2203     }
2204   }
2205 
2206   PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
2207     switch (type) {
2208       case PREMIUM_RATE:
2209         return metadata.getPremiumRate();
2210       case TOLL_FREE:
2211         return metadata.getTollFree();
2212       case MOBILE:
2213         return metadata.getMobile();
2214       case FIXED_LINE:
2215       case FIXED_LINE_OR_MOBILE:
2216         return metadata.getFixedLine();
2217       case SHARED_COST:
2218         return metadata.getSharedCost();
2219       case VOIP:
2220         return metadata.getVoip();
2221       case PERSONAL_NUMBER:
2222         return metadata.getPersonalNumber();
2223       case PAGER:
2224         return metadata.getPager();
2225       case UAN:
2226         return metadata.getUan();
2227       case VOICEMAIL:
2228         return metadata.getVoicemail();
2229       default:
2230         return metadata.getGeneralDesc();
2231     }
2232   }
2233 
2234   /**
2235    * Gets the type of a valid phone number.
2236    *
2237    * @param number  the phone number that we want to know the type
2238    * @return  the type of the phone number, or UNKNOWN if it is invalid
2239    */
2240   public PhoneNumberType getNumberType(PhoneNumber number) {
2241     String regionCode = getRegionCodeForNumber(number);
2242     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
2243     if (metadata == null) {
2244       return PhoneNumberType.UNKNOWN;
2245     }
2246     String nationalSignificantNumber = getNationalSignificantNumber(number);
2247     return getNumberTypeHelper(nationalSignificantNumber, metadata);
2248   }
2249 
2250   private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
2251     if (!isNumberMatchingDesc(nationalNumber, metadata.getGeneralDesc())) {
2252       return PhoneNumberType.UNKNOWN;
2253     }
2254 
2255     if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
2256       return PhoneNumberType.PREMIUM_RATE;
2257     }
2258     if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
2259       return PhoneNumberType.TOLL_FREE;
2260     }
2261     if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
2262       return PhoneNumberType.SHARED_COST;
2263     }
2264     if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
2265       return PhoneNumberType.VOIP;
2266     }
2267     if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
2268       return PhoneNumberType.PERSONAL_NUMBER;
2269     }
2270     if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
2271       return PhoneNumberType.PAGER;
2272     }
2273     if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
2274       return PhoneNumberType.UAN;
2275     }
2276     if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
2277       return PhoneNumberType.VOICEMAIL;
2278     }
2279 
2280     boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
2281     if (isFixedLine) {
2282       if (metadata.getSameMobileAndFixedLinePattern()) {
2283         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2284       } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2285         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2286       }
2287       return PhoneNumberType.FIXED_LINE;
2288     }
2289     // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
2290     // mobile and fixed line aren't the same.
2291     if (!metadata.getSameMobileAndFixedLinePattern()
2292         && isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2293       return PhoneNumberType.MOBILE;
2294     }
2295     return PhoneNumberType.UNKNOWN;
2296   }
2297 
2298   /**
2299    * Returns the metadata for the given region code or {@code null} if the region code is invalid or
2300    * unknown.
2301    *
2302    * @throws MissingMetadataException if the region code is valid, but metadata cannot be found.
2303    */
2304   PhoneMetadata getMetadataForRegion(String regionCode) {
2305     if (!isValidRegionCode(regionCode)) {
2306       return null;
2307     }
2308     PhoneMetadata phoneMetadata = metadataSource.getMetadataForRegion(regionCode);
2309     ensureMetadataIsNonNull(phoneMetadata, "Missing metadata for region code " + regionCode);
2310     return phoneMetadata;
2311   }
2312 
2313   /**
2314    * Returns the metadata for the given country calling code or {@code null} if the country calling
2315    * code is invalid or unknown.
2316    *
2317    * @throws MissingMetadataException if the country calling code is valid, but metadata cannot be
2318    *     found.
2319    */
2320   PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
2321     if (!countryCodesForNonGeographicalRegion.contains(countryCallingCode)) {
2322       return null;
2323     }
2324     PhoneMetadata phoneMetadata = metadataSource.getMetadataForNonGeographicalRegion(
2325         countryCallingCode);
2326     ensureMetadataIsNonNull(phoneMetadata,
2327         "Missing metadata for country code " + countryCallingCode);
2328     return phoneMetadata;
2329   }
2330 
2331   private static void ensureMetadataIsNonNull(PhoneMetadata phoneMetadata, String message) {
2332     if (phoneMetadata == null) {
2333       throw new MissingMetadataException(message);
2334     }
2335   }
2336 
2337   boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2338     // Check if any possible number lengths are present; if so, we use them to avoid checking the
2339     // validation pattern if they don't match. If they are absent, this means they match the general
2340     // description, which we have already checked before checking a specific number type.
2341     int actualLength = nationalNumber.length();
2342     List<Integer> possibleLengths = numberDesc.getPossibleLengthList();
2343     if (possibleLengths.size() > 0 && !possibleLengths.contains(actualLength)) {
2344       return false;
2345     }
2346     return matcherApi.matchNationalNumber(nationalNumber, numberDesc, false);
2347   }
2348 
2349   /**
2350    * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2351    * is actually in use, which is impossible to tell by just looking at a number itself. It only
2352    * verifies whether the parsed, canonicalised number is valid: not whether a particular series of
2353    * digits entered by the user is diallable from the region provided when parsing. For example, the
2354    * number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national
2355    * significant number "789272696". This is valid, while the original string is not diallable.
2356    *
2357    * @param number  the phone number that we want to validate
2358    * @return  a boolean that indicates whether the number is of a valid pattern
2359    */
2360   public boolean isValidNumber(PhoneNumber number) {
2361     String regionCode = getRegionCodeForNumber(number);
2362     return isValidNumberForRegion(number, regionCode);
2363   }
2364 
2365   /**
2366    * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2367    * is actually in use, which is impossible to tell by just looking at a number itself. If the
2368    * country calling code is not the same as the country calling code for the region, this
2369    * immediately exits with false. After this, the specific number pattern rules for the region are
2370    * examined. This is useful for determining for example whether a particular number is valid for
2371    * Canada, rather than just a valid NANPA number.
2372    * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2373    * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2374    * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2375    * undesirable.
2376    *
2377    * @param number  the phone number that we want to validate
2378    * @param regionCode  the region that we want to validate the phone number for
2379    * @return  a boolean that indicates whether the number is of a valid pattern
2380    */
2381   public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2382     int countryCode = number.getCountryCode();
2383     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2384     if ((metadata == null)
2385         || (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
2386          && countryCode != getCountryCodeForValidRegion(regionCode))) {
2387       // Either the region code was invalid, or the country calling code for this number does not
2388       // match that of the region code.
2389       return false;
2390     }
2391     String nationalSignificantNumber = getNationalSignificantNumber(number);
2392     return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
2393   }
2394 
2395   /**
2396    * Returns the region where a phone number is from. This could be used for geocoding at the region
2397    * level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid
2398    * numbers).
2399    *
2400    * @param number  the phone number whose origin we want to know
2401    * @return  the region where the phone number is from, or null if no region matches this calling
2402    *     code
2403    */
2404   public String getRegionCodeForNumber(PhoneNumber number) {
2405     int countryCode = number.getCountryCode();
2406     List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
2407     if (regions == null) {
2408       logger.log(Level.INFO, "Missing/invalid country_code (" + countryCode + ")");
2409       return null;
2410     }
2411     if (regions.size() == 1) {
2412       return regions.get(0);
2413     } else {
2414       return getRegionCodeForNumberFromRegionList(number, regions);
2415     }
2416   }
2417 
2418   private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
2419                                                       List<String> regionCodes) {
2420     String nationalNumber = getNationalSignificantNumber(number);
2421     for (String regionCode : regionCodes) {
2422       // If leadingDigits is present, use this. Otherwise, do full validation.
2423       // Metadata cannot be null because the region codes come from the country calling code map.
2424       PhoneMetadata metadata = getMetadataForRegion(regionCode);
2425       if (metadata.hasLeadingDigits()) {
2426         if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
2427                 .matcher(nationalNumber).lookingAt()) {
2428           return regionCode;
2429         }
2430       } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
2431         return regionCode;
2432       }
2433     }
2434     return null;
2435   }
2436 
2437   /**
2438    * Returns the region code that matches the specific country calling code. In the case of no
2439    * region code being found, ZZ will be returned. In the case of multiple regions, the one
2440    * designated in the metadata as the "main" region for this calling code will be returned. If the
2441    * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
2442    * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
2443    * the value for World in the UN M.49 schema).
2444    */
2445   public String getRegionCodeForCountryCode(int countryCallingCode) {
2446     List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2447     return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
2448   }
2449 
2450   /**
2451    * Returns a list with the region codes that match the specific country calling code. For
2452    * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2453    * of no region code being found, an empty list is returned.
2454    */
2455   public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2456     List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2457     return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2458                                                             : regionCodes);
2459   }
2460 
2461   /**
2462    * Returns the country calling code for a specific region. For example, this would be 1 for the
2463    * United States, and 64 for New Zealand.
2464    *
2465    * @param regionCode  the region that we want to get the country calling code for
2466    * @return  the country calling code for the region denoted by regionCode
2467    */
2468   public int getCountryCodeForRegion(String regionCode) {
2469     if (!isValidRegionCode(regionCode)) {
2470       logger.log(Level.WARNING,
2471                  "Invalid or missing region code ("
2472                   + ((regionCode == null) ? "null" : regionCode)
2473                   + ") provided.");
2474       return 0;
2475     }
2476     return getCountryCodeForValidRegion(regionCode);
2477   }
2478 
2479   /**
2480    * Returns the country calling code for a specific region. For example, this would be 1 for the
2481    * United States, and 64 for New Zealand. Assumes the region is already valid.
2482    *
2483    * @param regionCode  the region that we want to get the country calling code for
2484    * @return  the country calling code for the region denoted by regionCode
2485    * @throws IllegalArgumentException if the region is invalid
2486    */
2487   private int getCountryCodeForValidRegion(String regionCode) {
2488     PhoneMetadata metadata = getMetadataForRegion(regionCode);
2489     if (metadata == null) {
2490       throw new IllegalArgumentException("Invalid region code: " + regionCode);
2491     }
2492     return metadata.getCountryCode();
2493   }
2494 
2495   /**
2496    * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2497    * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2498    * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2499    * present, we return null.
2500    *
2501    * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2502    * national dialling prefix is used only for certain types of numbers. Use the library's
2503    * formatting functions to prefix the national prefix when required.
2504    *
2505    * @param regionCode  the region that we want to get the dialling prefix for
2506    * @param stripNonDigits  true to strip non-digits from the national dialling prefix
2507    * @return  the dialling prefix for the region denoted by regionCode
2508    */
2509   public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2510     PhoneMetadata metadata = getMetadataForRegion(regionCode);
2511     if (metadata == null) {
2512       logger.log(Level.WARNING,
2513                  "Invalid or missing region code ("
2514                   + ((regionCode == null) ? "null" : regionCode)
2515                   + ") provided.");
2516       return null;
2517     }
2518     String nationalPrefix = metadata.getNationalPrefix();
2519     // If no national prefix was found, we return null.
2520     if (nationalPrefix.length() == 0) {
2521       return null;
2522     }
2523     if (stripNonDigits) {
2524       // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2525       // to be removed here as well.
2526       nationalPrefix = nationalPrefix.replace("~", "");
2527     }
2528     return nationalPrefix;
2529   }
2530 
2531   /**
2532    * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2533    *
2534    * @return  true if regionCode is one of the regions under NANPA
2535    */
2536   public boolean isNANPACountry(String regionCode) {
2537     return nanpaRegions.contains(regionCode);
2538   }
2539 
2540   /**
2541    * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2542    * number will start with at least 3 digits and will have three or more alpha characters. This
2543    * does not do region-specific checks - to work out if this number is actually valid for a region,
2544    * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2545    * {@link #isValidNumber} should be used.
2546    *
2547    * @param number  the number that needs to be checked
2548    * @return  true if the number is a valid vanity number
2549    */
2550   public boolean isAlphaNumber(CharSequence number) {
2551     if (!isViablePhoneNumber(number)) {
2552       // Number is too short, or doesn't match the basic phone number pattern.
2553       return false;
2554     }
2555     StringBuilder strippedNumber = new StringBuilder(number);
2556     maybeStripExtension(strippedNumber);
2557     return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2558   }
2559 
2560   /**
2561    * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2562    * for failure, this method returns true if the number is either a possible fully-qualified number
2563    * (containing the area code and country code), or if the number could be a possible local number
2564    * (with a country code, but missing an area code). Local numbers are considered possible if they
2565    * could be possibly dialled in this format: if the area code is needed for a call to connect, the
2566    * number is not considered possible without it.
2567    *
2568    * @param number  the number that needs to be checked
2569    * @return  true if the number is possible
2570    */
2571   public boolean isPossibleNumber(PhoneNumber number) {
2572     ValidationResult result = isPossibleNumberWithReason(number);
2573     return result == ValidationResult.IS_POSSIBLE
2574         || result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY;
2575   }
2576 
2577   /**
2578    * Convenience wrapper around {@link #isPossibleNumberForTypeWithReason}. Instead of returning the
2579    * reason for failure, this method returns true if the number is either a possible fully-qualified
2580    * number (containing the area code and country code), or if the number could be a possible local
2581    * number (with a country code, but missing an area code). Local numbers are considered possible
2582    * if they could be possibly dialled in this format: if the area code is needed for a call to
2583    * connect, the number is not considered possible without it.
2584    *
2585    * @param number  the number that needs to be checked
2586    * @param type  the type we are interested in
2587    * @return  true if the number is possible for this particular type
2588    */
2589   public boolean isPossibleNumberForType(PhoneNumber number, PhoneNumberType type) {
2590     ValidationResult result = isPossibleNumberForTypeWithReason(number, type);
2591     return result == ValidationResult.IS_POSSIBLE
2592         || result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY;
2593   }
2594 
2595   /**
2596    * Helper method to check a number against possible lengths for this region, based on the metadata
2597    * being passed in, and determine whether it matches, or is too short or too long.
2598    */
2599   private ValidationResult testNumberLength(CharSequence number, PhoneMetadata metadata) {
2600     return testNumberLength(number, metadata, PhoneNumberType.UNKNOWN);
2601   }
2602 
2603   /**
2604    * Helper method to check a number against possible lengths for this number type, and determine
2605    * whether it matches, or is too short or too long.
2606    */
2607   private ValidationResult testNumberLength(
2608       CharSequence number, PhoneMetadata metadata, PhoneNumberType type) {
2609     PhoneNumberDesc descForType = getNumberDescByType(metadata, type);
2610     // There should always be "possibleLengths" set for every element. This is declared in the XML
2611     // schema which is verified by PhoneNumberMetadataSchemaTest.
2612     // For size efficiency, where a sub-description (e.g. fixed-line) has the same possibleLengths
2613     // as the parent, this is missing, so we fall back to the general desc (where no numbers of the
2614     // type exist at all, there is one possible length (-1) which is guaranteed not to match the
2615     // length of any real phone number).
2616     List<Integer> possibleLengths = descForType.getPossibleLengthList().isEmpty()
2617         ? metadata.getGeneralDesc().getPossibleLengthList() : descForType.getPossibleLengthList();
2618 
2619     List<Integer> localLengths = descForType.getPossibleLengthLocalOnlyList();
2620 
2621     if (type == PhoneNumberType.FIXED_LINE_OR_MOBILE) {
2622       if (!descHasPossibleNumberData(getNumberDescByType(metadata, PhoneNumberType.FIXED_LINE))) {
2623         // The rare case has been encountered where no fixedLine data is available (true for some
2624         // non-geographical entities), so we just check mobile.
2625         return testNumberLength(number, metadata, PhoneNumberType.MOBILE);
2626       } else {
2627         PhoneNumberDesc mobileDesc = getNumberDescByType(metadata, PhoneNumberType.MOBILE);
2628         if (descHasPossibleNumberData(mobileDesc)) {
2629           // Merge the mobile data in if there was any. We have to make a copy to do this.
2630           possibleLengths = new ArrayList<>(possibleLengths);
2631           // Note that when adding the possible lengths from mobile, we have to again check they
2632           // aren't empty since if they are this indicates they are the same as the general desc and
2633           // should be obtained from there.
2634           possibleLengths.addAll(mobileDesc.getPossibleLengthCount() == 0
2635               ? metadata.getGeneralDesc().getPossibleLengthList()
2636               : mobileDesc.getPossibleLengthList());
2637           // The current list is sorted; we need to merge in the new list and re-sort (duplicates
2638           // are okay). Sorting isn't so expensive because the lists are very small.
2639           Collections.sort(possibleLengths);
2640 
2641           if (localLengths.isEmpty()) {
2642             localLengths = mobileDesc.getPossibleLengthLocalOnlyList();
2643           } else {
2644             localLengths = new ArrayList<>(localLengths);
2645             localLengths.addAll(mobileDesc.getPossibleLengthLocalOnlyList());
2646             Collections.sort(localLengths);
2647           }
2648         }
2649       }
2650     }
2651 
2652     // If the type is not supported at all (indicated by the possible lengths containing -1 at this
2653     // point) we return invalid length.
2654     if (possibleLengths.get(0) == -1) {
2655       return ValidationResult.INVALID_LENGTH;
2656     }
2657 
2658     int actualLength = number.length();
2659     // This is safe because there is never an overlap beween the possible lengths and the local-only
2660     // lengths; this is checked at build time.
2661     if (localLengths.contains(actualLength)) {
2662       return ValidationResult.IS_POSSIBLE_LOCAL_ONLY;
2663     }
2664 
2665     int minimumLength = possibleLengths.get(0);
2666     if (minimumLength == actualLength) {
2667       return ValidationResult.IS_POSSIBLE;
2668     } else if (minimumLength > actualLength) {
2669       return ValidationResult.TOO_SHORT;
2670     } else if (possibleLengths.get(possibleLengths.size() - 1) < actualLength) {
2671       return ValidationResult.TOO_LONG;
2672     }
2673     // We skip the first element; we've already checked it.
2674     return possibleLengths.subList(1, possibleLengths.size()).contains(actualLength)
2675         ? ValidationResult.IS_POSSIBLE : ValidationResult.INVALID_LENGTH;
2676   }
2677 
2678   /**
2679    * Check whether a phone number is a possible number. It provides a more lenient check than
2680    * {@link #isValidNumber} in the following sense:
2681    * <ol>
2682    *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
2683    *        digits of the number.
2684    *   <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2685    *        applies to all types of phone numbers in a region. Therefore, it is much faster than
2686    *        isValidNumber.
2687    *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
2688    *        which together with subscriber number constitute the national significant number. It is
2689    *        sometimes okay to dial only the subscriber number when dialing in the same area. This
2690    *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
2691    *        passed in. On the other hand, because isValidNumber validates using information on both
2692    *        starting digits (for fixed line numbers, that would most likely be area codes) and
2693    *        length (obviously includes the length of area codes for fixed line numbers), it will
2694    *        return false for the subscriber-number-only version.
2695    * </ol>
2696    * @param number  the number that needs to be checked
2697    * @return  a ValidationResult object which indicates whether the number is possible
2698    */
2699   public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2700     return isPossibleNumberForTypeWithReason(number, PhoneNumberType.UNKNOWN);
2701   }
2702 
2703   /**
2704    * Check whether a phone number is a possible number of a particular type. For types that don't
2705    * exist in a particular region, this will return a result that isn't so useful; it is recommended
2706    * that you use {@link #getSupportedTypesForRegion} or {@link #getSupportedTypesForNonGeoEntity}
2707    * respectively before calling this method to determine whether you should call it for this number
2708    * at all.
2709    *
2710    * This provides a more lenient check than {@link #isValidNumber} in the following sense:
2711    *
2712    * <ol>
2713    *   <li> It only checks the length of phone numbers. In particular, it doesn't check starting
2714    *        digits of the number.
2715    *   <li> For some numbers (particularly fixed-line), many regions have the concept of area code,
2716    *        which together with subscriber number constitute the national significant number. It is
2717    *        sometimes okay to dial only the subscriber number when dialing in the same area. This
2718    *        function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is
2719    *        passed in. On the other hand, because isValidNumber validates using information on both
2720    *        starting digits (for fixed line numbers, that would most likely be area codes) and
2721    *        length (obviously includes the length of area codes for fixed line numbers), it will
2722    *        return false for the subscriber-number-only version.
2723    * </ol>
2724    *
2725    * @param number  the number that needs to be checked
2726    * @param type  the type we are interested in
2727    * @return  a ValidationResult object which indicates whether the number is possible
2728    */
2729   public ValidationResult isPossibleNumberForTypeWithReason(
2730       PhoneNumber number, PhoneNumberType type) {
2731     String nationalNumber = getNationalSignificantNumber(number);
2732     int countryCode = number.getCountryCode();
2733     // Note: For regions that share a country calling code, like NANPA numbers, we just use the
2734     // rules from the default region (US in this case) since the getRegionCodeForNumber will not
2735     // work if the number is possible but not valid. There is in fact one country calling code (290)
2736     // where the possible number pattern differs between various regions (Saint Helena and Tristan
2737     // da Cuñha), but this is handled by putting all possible lengths for any country with this
2738     // country calling code in the metadata for the default region in this case.
2739     if (!hasValidCountryCallingCode(countryCode)) {
2740       return ValidationResult.INVALID_COUNTRY_CODE;
2741     }
2742     String regionCode = getRegionCodeForCountryCode(countryCode);
2743     // Metadata cannot be null because the country calling code is valid.
2744     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2745     return testNumberLength(nationalNumber, metadata, type);
2746   }
2747 
2748   /**
2749    * Check whether a phone number is a possible number given a number in the form of a string, and
2750    * the region where the number could be dialed from. It provides a more lenient check than
2751    * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
2752    *
2753    * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
2754    * with the resultant PhoneNumber object.
2755    *
2756    * @param number  the number that needs to be checked
2757    * @param regionDialingFrom  the region that we are expecting the number to be dialed from.
2758    *     Note this is different from the region where the number belongs.  For example, the number
2759    *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2760    *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2761    *     region which uses an international dialling prefix of 00. When it is written as
2762    *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2763    *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
2764    *     specific).
2765    * @return  true if the number is possible
2766    */
2767   public boolean isPossibleNumber(CharSequence number, String regionDialingFrom) {
2768     try {
2769       return isPossibleNumber(parse(number, regionDialingFrom));
2770     } catch (NumberParseException e) {
2771       return false;
2772     }
2773   }
2774 
2775   /**
2776    * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2777    * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2778    * the PhoneNumber object passed in will not be modified.
2779    * @param number  a PhoneNumber object which contains a number that is too long to be valid
2780    * @return  true if a valid phone number can be successfully extracted
2781    */
2782   public boolean truncateTooLongNumber(PhoneNumber number) {
2783     if (isValidNumber(number)) {
2784       return true;
2785     }
2786     PhoneNumber numberCopy = new PhoneNumber();
2787     numberCopy.mergeFrom(number);
2788     long nationalNumber = number.getNationalNumber();
2789     do {
2790       nationalNumber /= 10;
2791       numberCopy.setNationalNumber(nationalNumber);
2792       if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT
2793           || nationalNumber == 0) {
2794         return false;
2795       }
2796     } while (!isValidNumber(numberCopy));
2797     number.setNationalNumber(nationalNumber);
2798     return true;
2799   }
2800 
2801   /**
2802    * Gets an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
2803    *
2804    * @param regionCode  the region where the phone number is being entered
2805    * @return  an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2806    *     to format phone numbers in the specific region "as you type"
2807    */
2808   public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
2809     return new AsYouTypeFormatter(regionCode);
2810   }
2811 
2812   // Extracts country calling code from fullNumber, returns it and places the remaining number in
2813   // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2814   // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2815   // unmodified.
2816   int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2817     if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2818       // Country codes do not begin with a '0'.
2819       return 0;
2820     }
2821     int potentialCountryCode;
2822     int numberLength = fullNumber.length();
2823     for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
2824       potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2825       if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
2826         nationalNumber.append(fullNumber.substring(i));
2827         return potentialCountryCode;
2828       }
2829     }
2830     return 0;
2831   }
2832 
2833   /**
2834    * Tries to extract a country calling code from a number. This method will return zero if no
2835    * country calling code is considered to be present. Country calling codes are extracted in the
2836    * following ways:
2837    * <ul>
2838    *  <li> by stripping the international dialing prefix of the region the person is dialing from,
2839    *       if this is present in the number, and looking at the next digits
2840    *  <li> by stripping the '+' sign if present and then looking at the next digits
2841    *  <li> by comparing the start of the number and the country calling code of the default region.
2842    *       If the number is not considered possible for the numbering plan of the default region
2843    *       initially, but starts with the country calling code of this region, validation will be
2844    *       reattempted after stripping this country calling code. If this number is considered a
2845    *       possible number, then the first digits will be considered the country calling code and
2846    *       removed as such.
2847    * </ul>
2848    * It will throw a NumberParseException if the number starts with a '+' but the country calling
2849    * code supplied after this does not match that of any known region.
2850    *
2851    * @param number  non-normalized telephone number that we wish to extract a country calling
2852    *     code from - may begin with '+'
2853    * @param defaultRegionMetadata  metadata about the region this number may be from
2854    * @param nationalNumber  a string buffer to store the national significant number in, in the case
2855    *     that a country calling code was extracted. The number is appended to any existing contents.
2856    *     If no country calling code was extracted, this will be left unchanged.
2857    * @param keepRawInput  true if the country_code_source and preferred_carrier_code fields of
2858    *     phoneNumber should be populated.
2859    * @param phoneNumber  the PhoneNumber object where the country_code and country_code_source need
2860    *     to be populated. Note the country_code is always populated, whereas country_code_source is
2861    *     only populated when keepCountryCodeSource is true.
2862    * @return  the country calling code extracted or 0 if none could be extracted
2863    */
2864   // @VisibleForTesting
2865   int maybeExtractCountryCode(CharSequence number, PhoneMetadata defaultRegionMetadata,
2866                               StringBuilder nationalNumber, boolean keepRawInput,
2867                               PhoneNumber phoneNumber)
2868       throws NumberParseException {
2869     if (number.length() == 0) {
2870       return 0;
2871     }
2872     StringBuilder fullNumber = new StringBuilder(number);
2873     // Set the default prefix to be something that will never match.
2874     String possibleCountryIddPrefix = "NonMatch";
2875     if (defaultRegionMetadata != null) {
2876       possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
2877     }
2878 
2879     CountryCodeSource countryCodeSource =
2880         maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
2881     if (keepRawInput) {
2882       phoneNumber.setCountryCodeSource(countryCodeSource);
2883     }
2884     if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2885       if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
2886         throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2887                                        "Phone number had an IDD, but after this was not "
2888                                        + "long enough to be a viable phone number.");
2889       }
2890       int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
2891       if (potentialCountryCode != 0) {
2892         phoneNumber.setCountryCode(potentialCountryCode);
2893         return potentialCountryCode;
2894       }
2895 
2896       // If this fails, they must be using a strange country calling code that we don't recognize,
2897       // or that doesn't exist.
2898       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2899                                      "Country calling code supplied was not recognised.");
2900     } else if (defaultRegionMetadata != null) {
2901       // Check to see if the number starts with the country calling code for the default region. If
2902       // so, we remove the country calling code, and do some checks on the validity of the number
2903       // before and after.
2904       int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2905       String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2906       String normalizedNumber = fullNumber.toString();
2907       if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2908         StringBuilder potentialNationalNumber =
2909             new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
2910         PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2911         maybeStripNationalPrefixAndCarrierCode(
2912             potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2913         // If the number was not valid before but is valid now, or if it was too long before, we
2914         // consider the number with the country calling code stripped to be a better result and
2915         // keep that instead.
2916         if ((!matcherApi.matchNationalNumber(fullNumber, generalDesc, false)
2917                 && matcherApi.matchNationalNumber(potentialNationalNumber, generalDesc, false))
2918             || testNumberLength(fullNumber, defaultRegionMetadata) == ValidationResult.TOO_LONG) {
2919           nationalNumber.append(potentialNationalNumber);
2920           if (keepRawInput) {
2921             phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
2922           }
2923           phoneNumber.setCountryCode(defaultCountryCode);
2924           return defaultCountryCode;
2925         }
2926       }
2927     }
2928     // No country calling code present.
2929     phoneNumber.setCountryCode(0);
2930     return 0;
2931   }
2932 
2933   /**
2934    * Strips the IDD from the start of the number if present. Helper function used by
2935    * maybeStripInternationalPrefixAndNormalize.
2936    */
2937   private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
2938     Matcher m = iddPattern.matcher(number);
2939     if (m.lookingAt()) {
2940       int matchEnd = m.end();
2941       // Only strip this if the first digit after the match is not a 0, since country calling codes
2942       // cannot begin with 0.
2943       Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
2944       if (digitMatcher.find()) {
2945         String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
2946         if (normalizedGroup.equals("0")) {
2947           return false;
2948         }
2949       }
2950       number.delete(0, matchEnd);
2951       return true;
2952     }
2953     return false;
2954   }
2955 
2956   /**
2957    * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2958    * the resulting number, and indicates if an international prefix was present.
2959    *
2960    * @param number  the non-normalized telephone number that we wish to strip any international
2961    *     dialing prefix from
2962    * @param possibleIddPrefix  the international direct dialing prefix from the region we
2963    *     think this number may be dialed in
2964    * @return  the corresponding CountryCodeSource if an international dialing prefix could be
2965    *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2966    *     not seem to be in international format
2967    */
2968   // @VisibleForTesting
2969   CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2970       StringBuilder number,
2971       String possibleIddPrefix) {
2972     if (number.length() == 0) {
2973       return CountryCodeSource.FROM_DEFAULT_COUNTRY;
2974     }
2975     // Check to see if the number begins with one or more plus signs.
2976     Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2977     if (m.lookingAt()) {
2978       number.delete(0, m.end());
2979       // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
2980       normalize(number);
2981       return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
2982     }
2983     // Attempt to parse the first digits as an international prefix.
2984     Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
2985     normalize(number);
2986     return parsePrefixAsIdd(iddPattern, number)
2987            ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2988            : CountryCodeSource.FROM_DEFAULT_COUNTRY;
2989   }
2990 
2991   /**
2992    * Strips any national prefix (such as 0, 1) present in the number provided.
2993    *
2994    * @param number  the normalized telephone number that we wish to strip any national
2995    *     dialing prefix from
2996    * @param metadata  the metadata for the region that we think this number is from
2997    * @param carrierCode  a place to insert the carrier code if one is extracted
2998    * @return true if a national prefix or carrier code (or both) could be extracted
2999    */
3000   // @VisibleForTesting
3001   boolean maybeStripNationalPrefixAndCarrierCode(
3002       StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
3003     int numberLength = number.length();
3004     String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
3005     if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
3006       // Early return for numbers of zero length.
3007       return false;
3008     }
3009     // Attempt to parse the first digits as a national prefix.
3010     Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
3011     if (prefixMatcher.lookingAt()) {
3012       PhoneNumberDesc generalDesc = metadata.getGeneralDesc();
3013       // Check if the original number is viable.
3014       boolean isViableOriginalNumber = matcherApi.matchNationalNumber(number, generalDesc, false);
3015       // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
3016       // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
3017       // remove the national prefix.
3018       int numOfGroups = prefixMatcher.groupCount();
3019       String transformRule = metadata.getNationalPrefixTransformRule();
3020       if (transformRule == null || transformRule.length() == 0
3021           || prefixMatcher.group(numOfGroups) == null) {
3022         // If the original number was viable, and the resultant number is not, we return.
3023         if (isViableOriginalNumber
3024             && !matcherApi.matchNationalNumber(
3025                 number.substring(prefixMatcher.end()), generalDesc, false)) {
3026           return false;
3027         }
3028         if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
3029           carrierCode.append(prefixMatcher.group(1));
3030         }
3031         number.delete(0, prefixMatcher.end());
3032         return true;
3033       } else {
3034         // Check that the resultant number is still viable. If not, return. Check this by copying
3035         // the string buffer and making the transformation on the copy first.
3036         StringBuilder transformedNumber = new StringBuilder(number);
3037         transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
3038         if (isViableOriginalNumber
3039             && !matcherApi.matchNationalNumber(transformedNumber.toString(), generalDesc, false)) {
3040           return false;
3041         }
3042         if (carrierCode != null && numOfGroups > 1) {
3043           carrierCode.append(prefixMatcher.group(1));
3044         }
3045         number.replace(0, number.length(), transformedNumber.toString());
3046         return true;
3047       }
3048     }
3049     return false;
3050   }
3051 
3052   /**
3053    * Strips any extension (as in, the part of the number dialled after the call is connected,
3054    * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
3055    *
3056    * @param number  the non-normalized telephone number that we wish to strip the extension from
3057    * @return  the phone extension
3058    */
3059   // @VisibleForTesting
3060   String maybeStripExtension(StringBuilder number) {
3061     Matcher m = EXTN_PATTERN.matcher(number);
3062     // If we find a potential extension, and the number preceding this is a viable number, we assume
3063     // it is an extension.
3064     if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
3065       // The numbers are captured into groups in the regular expression.
3066       for (int i = 1, length = m.groupCount(); i <= length; i++) {
3067         if (m.group(i) != null) {
3068           // We go through the capturing groups until we find one that captured some digits. If none
3069           // did, then we will return the empty string.
3070           String extension = m.group(i);
3071           number.delete(m.start(), number.length());
3072           return extension;
3073         }
3074       }
3075     }
3076     return "";
3077   }
3078 
3079   /**
3080    * Checks to see that the region code used is valid, or if it is not valid, that the number to
3081    * parse starts with a + symbol so that we can attempt to infer the region from the number.
3082    * Returns false if it cannot use the region provided and the region cannot be inferred.
3083    */
3084   private boolean checkRegionForParsing(CharSequence numberToParse, String defaultRegion) {
3085     if (!isValidRegionCode(defaultRegion)) {
3086       // If the number is null or empty, we can't infer the region.
3087       if ((numberToParse == null) || (numberToParse.length() == 0)
3088           || !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
3089         return false;
3090       }
3091     }
3092     return true;
3093   }
3094 
3095   /**
3096    * Parses a string and returns it as a phone number in proto buffer format. The method is quite
3097    * lenient and looks for a number in the input text (raw input) and does not check whether the
3098    * string is definitely only a phone number. To do this, it ignores punctuation and white-space,
3099    * as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits.
3100    * It will accept a number in any format (E164, national, international etc), assuming it can be
3101    * interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters
3102    * into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
3103    *
3104    * <p> This method will throw a {@link com.google.i18n.phonenumbers.NumberParseException} if the
3105    * number is not considered to be a possible number. Note that validation of whether the number
3106    * is actually a valid number for a particular region is not performed. This can be done
3107    * separately with {@link #isValidNumber}.
3108    *
3109    * <p> Note this method canonicalizes the phone number such that different representations can be
3110    * easily compared, no matter what form it was originally entered in (e.g. national,
3111    * international). If you want to record context about the number being parsed, such as the raw
3112    * input that was entered, how the country code was derived etc. then call {@link
3113    * #parseAndKeepRawInput} instead.
3114    *
3115    * @param numberToParse  number that we are attempting to parse. This can contain formatting such
3116    *     as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966
3117    *     format.
3118    * @param defaultRegion  region that we are expecting the number to be from. This is only used if
3119    *     the number being parsed is not written in international format. The country_code for the
3120    *     number in this case would be stored as that of the default region supplied. If the number
3121    *     is guaranteed to start with a '+' followed by the country calling code, then RegionCode.ZZ
3122    *     or null can be supplied.
3123    * @return  a phone number proto buffer filled with the parsed number
3124    * @throws NumberParseException  if the string is not considered to be a viable phone number (e.g.
3125    *     too few or too many digits) or if no default region was supplied and the number is not in
3126    *     international format (does not start with +)
3127    */
3128   public PhoneNumber parse(CharSequence numberToParse, String defaultRegion)
3129       throws NumberParseException {
3130     PhoneNumber phoneNumber = new PhoneNumber();
3131     parse(numberToParse, defaultRegion, phoneNumber);
3132     return phoneNumber;
3133   }
3134 
3135   /**
3136    * Same as {@link #parse(CharSequence, String)}, but accepts mutable PhoneNumber as a
3137    * parameter to decrease object creation when invoked many times.
3138    */
3139   public void parse(CharSequence numberToParse, String defaultRegion, PhoneNumber phoneNumber)
3140       throws NumberParseException {
3141     parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
3142   }
3143 
3144   /**
3145    * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
3146    * in that it always populates the raw_input field of the protocol buffer with numberToParse as
3147    * well as the country_code_source field.
3148    *
3149    * @param numberToParse  number that we are attempting to parse. This can contain formatting such
3150    *     as +, ( and -, as well as a phone number extension.
3151    * @param defaultRegion  region that we are expecting the number to be from. This is only used if
3152    *     the number being parsed is not written in international format. The country calling code
3153    *     for the number in this case would be stored as that of the default region supplied.
3154    * @return  a phone number proto buffer filled with the parsed number
3155    * @throws NumberParseException  if the string is not considered to be a viable phone number or if
3156    *     no default region was supplied
3157    */
3158   public PhoneNumber parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion)
3159       throws NumberParseException {
3160     PhoneNumber phoneNumber = new PhoneNumber();
3161     parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
3162     return phoneNumber;
3163   }
3164 
3165   /**
3166    * Same as{@link #parseAndKeepRawInput(CharSequence, String)}, but accepts a mutable
3167    * PhoneNumber as a parameter to decrease object creation when invoked many times.
3168    */
3169   public void parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion,
3170                                    PhoneNumber phoneNumber)
3171       throws NumberParseException {
3172     parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
3173   }
3174 
3175   /**
3176    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
3177    * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
3178    * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
3179    *
3180    * @param text  the text to search for phone numbers, null for no text
3181    * @param defaultRegion  region that we are expecting the number to be from. This is only used if
3182    *     the number being parsed is not written in international format. The country_code for the
3183    *     number in this case would be stored as that of the default region supplied. May be null if
3184    *     only international numbers are expected.
3185    */
3186   public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
3187     return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
3188   }
3189 
3190   /**
3191    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
3192    *
3193    * @param text  the text to search for phone numbers, null for no text
3194    * @param defaultRegion  region that we are expecting the number to be from. This is only used if
3195    *     the number being parsed is not written in international format. The country_code for the
3196    *     number in this case would be stored as that of the default region supplied. May be null if
3197    *     only international numbers are expected.
3198    * @param leniency  the leniency to use when evaluating candidate phone numbers
3199    * @param maxTries  the maximum number of invalid numbers to try before giving up on the text.
3200    *     This is to cover degenerate cases where the text has a lot of false positives in it. Must
3201    *     be {@code >= 0}.
3202    */
3203   public Iterable<PhoneNumberMatch> findNumbers(
3204       final CharSequence text, final String defaultRegion, final Leniency leniency,
3205       final long maxTries) {
3206 
3207     return new Iterable<PhoneNumberMatch>() {
3208       @Override
3209       public Iterator<PhoneNumberMatch> iterator() {
3210         return new PhoneNumberMatcher(
3211             PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
3212       }
3213     };
3214   }
3215 
3216   /**
3217    * A helper function to set the values related to leading zeros in a PhoneNumber.
3218    */
3219   static void setItalianLeadingZerosForPhoneNumber(CharSequence nationalNumber,
3220       PhoneNumber phoneNumber) {
3221     if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') {
3222       phoneNumber.setItalianLeadingZero(true);
3223       int numberOfLeadingZeros = 1;
3224       // Note that if the national number is all "0"s, the last "0" is not counted as a leading
3225       // zero.
3226       while (numberOfLeadingZeros < nationalNumber.length() - 1
3227           && nationalNumber.charAt(numberOfLeadingZeros) == '0') {
3228         numberOfLeadingZeros++;
3229       }
3230       if (numberOfLeadingZeros != 1) {
3231         phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros);
3232       }
3233     }
3234   }
3235 
3236   /**
3237    * Parses a string and fills up the phoneNumber. This method is the same as the public
3238    * parse() method, with the exception that it allows the default region to be null, for use by
3239    * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
3240    * to be null or unknown ("ZZ").
3241    *
3242    * Note if any new field is added to this method that should always be filled in, even when
3243    * keepRawInput is false, it should also be handled in the copyCoreFieldsOnly() method.
3244    */
3245   private void parseHelper(CharSequence numberToParse, String defaultRegion,
3246       boolean keepRawInput, boolean checkRegion, PhoneNumber phoneNumber)
3247       throws NumberParseException {
3248     if (numberToParse == null) {
3249       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
3250                                      "The phone number supplied was null.");
3251     } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
3252       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
3253                                      "The string supplied was too long to parse.");
3254     }
3255 
3256     StringBuilder nationalNumber = new StringBuilder();
3257     String numberBeingParsed = numberToParse.toString();
3258     buildNationalNumberForParsing(numberBeingParsed, nationalNumber);
3259 
3260     if (!isViablePhoneNumber(nationalNumber)) {
3261       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
3262                                      "The string supplied did not seem to be a phone number.");
3263     }
3264 
3265     // Check the region supplied is valid, or that the extracted number starts with some sort of +
3266     // sign so the number's region can be determined.
3267     if (checkRegion && !checkRegionForParsing(nationalNumber, defaultRegion)) {
3268       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
3269                                      "Missing or invalid default region.");
3270     }
3271 
3272     if (keepRawInput) {
3273       phoneNumber.setRawInput(numberBeingParsed);
3274     }
3275     // Attempt to parse extension first, since it doesn't require region-specific data and we want
3276     // to have the non-normalised number here.
3277     String extension = maybeStripExtension(nationalNumber);
3278     if (extension.length() > 0) {
3279       phoneNumber.setExtension(extension);
3280     }
3281 
3282     PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
3283     // Check to see if the number is given in international format so we know whether this number is
3284     // from the default region or not.
3285     StringBuilder normalizedNationalNumber = new StringBuilder();
3286     int countryCode = 0;
3287     try {
3288       // TODO: This method should really just take in the string buffer that has already
3289       // been created, and just remove the prefix, rather than taking in a string and then
3290       // outputting a string buffer.
3291       countryCode = maybeExtractCountryCode(nationalNumber, regionMetadata,
3292                                             normalizedNationalNumber, keepRawInput, phoneNumber);
3293     } catch (NumberParseException e) {
3294       Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber);
3295       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE
3296           && matcher.lookingAt()) {
3297         // Strip the plus-char, and try again.
3298         countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
3299                                               regionMetadata, normalizedNationalNumber,
3300                                               keepRawInput, phoneNumber);
3301         if (countryCode == 0) {
3302           throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
3303                                          "Could not interpret numbers after plus-sign.");
3304         }
3305       } else {
3306         throw new NumberParseException(e.getErrorType(), e.getMessage());
3307       }
3308     }
3309     if (countryCode != 0) {
3310       String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
3311       if (!phoneNumberRegion.equals(defaultRegion)) {
3312         // Metadata cannot be null because the country calling code is valid.
3313         regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
3314       }
3315     } else {
3316       // If no extracted country calling code, use the region supplied instead. The national number
3317       // is just the normalized version of the number we were given to parse.
3318       normalizedNationalNumber.append(normalize(nationalNumber));
3319       if (defaultRegion != null) {
3320         countryCode = regionMetadata.getCountryCode();
3321         phoneNumber.setCountryCode(countryCode);
3322       } else if (keepRawInput) {
3323         phoneNumber.clearCountryCodeSource();
3324       }
3325     }
3326     if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
3327       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
3328                                      "The string supplied is too short to be a phone number.");
3329     }
3330     if (regionMetadata != null) {
3331       StringBuilder carrierCode = new StringBuilder();
3332       StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
3333       maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
3334       // We require that the NSN remaining after stripping the national prefix and carrier code be
3335       // long enough to be a possible length for the region. Otherwise, we don't do the stripping,
3336       // since the original number could be a valid short number.
3337       ValidationResult validationResult = testNumberLength(potentialNationalNumber, regionMetadata);
3338       if (validationResult != ValidationResult.TOO_SHORT
3339           && validationResult != ValidationResult.IS_POSSIBLE_LOCAL_ONLY
3340           && validationResult != ValidationResult.INVALID_LENGTH) {
3341         normalizedNationalNumber = potentialNationalNumber;
3342         if (keepRawInput && carrierCode.length() > 0) {
3343           phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
3344         }
3345       }
3346     }
3347     int lengthOfNationalNumber = normalizedNationalNumber.length();
3348     if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
3349       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
3350                                      "The string supplied is too short to be a phone number.");
3351     }
3352     if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
3353       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
3354                                      "The string supplied is too long to be a phone number.");
3355     }
3356     setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber, phoneNumber);
3357     phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
3358   }
3359 
3360   /**
3361    * Extracts the value of the phone-context parameter of numberToExtractFrom where the index of
3362    * ";phone-context=" is the parameter indexOfPhoneContext, following the syntax defined in
3363    * RFC3966.
3364    *
3365    * @return the extracted string (possibly empty), or null if no phone-context parameter is found.
3366    */
3367   private String extractPhoneContext(String numberToExtractFrom, int indexOfPhoneContext) {
3368     // If no phone-context parameter is present
3369     if (indexOfPhoneContext == -1) {
3370       return null;
3371     }
3372 
3373     int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
3374     // If phone-context parameter is empty
3375     if (phoneContextStart >= numberToExtractFrom.length()) {
3376       return "";
3377     }
3378 
3379     int phoneContextEnd = numberToExtractFrom.indexOf(';', phoneContextStart);
3380     // If phone-context is not the last parameter
3381     if (phoneContextEnd != -1) {
3382       return numberToExtractFrom.substring(phoneContextStart, phoneContextEnd);
3383     } else {
3384       return numberToExtractFrom.substring(phoneContextStart);
3385     }
3386   }
3387 
3388   /**
3389    * Returns whether the value of phoneContext follows the syntax defined in RFC3966.
3390    */
3391   private boolean isPhoneContextValid(String phoneContext) {
3392     if (phoneContext == null) {
3393       return true;
3394     }
3395     if (phoneContext.length() == 0) {
3396       return false;
3397     }
3398 
3399     // Does phone-context value match pattern of global-number-digits or domainname
3400     return RFC3966_GLOBAL_NUMBER_DIGITS_PATTERN.matcher(phoneContext).matches()
3401         || RFC3966_DOMAINNAME_PATTERN.matcher(phoneContext).matches();
3402   }
3403 
3404   /**
3405    * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
3406    * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
3407    */
3408   private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber)
3409       throws NumberParseException {
3410     int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
3411 
3412     String phoneContext = extractPhoneContext(numberToParse, indexOfPhoneContext);
3413     if (!isPhoneContextValid(phoneContext)) {
3414       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
3415           "The phone-context value is invalid.");
3416     }
3417     if (phoneContext != null) {
3418       // If the phone context contains a phone number prefix, we need to capture it, whereas domains
3419       // will be ignored.
3420       if (phoneContext.charAt(0) == PLUS_SIGN) {
3421         // Additional parameters might follow the phone context. If so, we will remove them here
3422         // because the parameters after phone context are not important for parsing the phone
3423         // number.
3424         nationalNumber.append(phoneContext);
3425       }
3426 
3427       // Now append everything between the "tel:" prefix and the phone-context. This should include
3428       // the national number, an optional extension or isdn-subaddress component. Note we also
3429       // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
3430       // In that case, we append everything from the beginning.
3431       int indexOfRfc3966Prefix = numberToParse.indexOf(RFC3966_PREFIX);
3432       int indexOfNationalNumber =
3433           (indexOfRfc3966Prefix >= 0) ? indexOfRfc3966Prefix + RFC3966_PREFIX.length() : 0;
3434       nationalNumber.append(numberToParse.substring(indexOfNationalNumber, indexOfPhoneContext));
3435     } else {
3436       // Extract a possible number from the string passed in (this strips leading characters that
3437       // could not be the start of a phone number.)
3438       nationalNumber.append(extractPossibleNumber(numberToParse));
3439     }
3440 
3441     // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
3442     // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
3443     int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
3444     if (indexOfIsdn > 0) {
3445       nationalNumber.delete(indexOfIsdn, nationalNumber.length());
3446     }
3447     // If both phone context and isdn-subaddress are absent but other parameters are present, the
3448     // parameters are left in nationalNumber. This is because we are concerned about deleting
3449     // content from a potential number string when there is no strong evidence that the number is
3450     // actually written in RFC3966.
3451   }
3452 
3453   /**
3454    * Returns a new phone number containing only the fields needed to uniquely identify a phone
3455    * number, rather than any fields that capture the context in which the phone number was created.
3456    * These fields correspond to those set in parse() rather than parseAndKeepRawInput().
3457    */
3458   private static PhoneNumber copyCoreFieldsOnly(PhoneNumber phoneNumberIn) {
3459     PhoneNumber phoneNumber = new PhoneNumber();
3460     phoneNumber.setCountryCode(phoneNumberIn.getCountryCode());
3461     phoneNumber.setNationalNumber(phoneNumberIn.getNationalNumber());
3462     if (phoneNumberIn.getExtension().length() > 0) {
3463       phoneNumber.setExtension(phoneNumberIn.getExtension());
3464     }
3465     if (phoneNumberIn.isItalianLeadingZero()) {
3466       phoneNumber.setItalianLeadingZero(true);
3467       // This field is only relevant if there are leading zeros at all.
3468       phoneNumber.setNumberOfLeadingZeros(phoneNumberIn.getNumberOfLeadingZeros());
3469     }
3470     return phoneNumber;
3471   }
3472 
3473   /**
3474    * Takes two phone numbers and compares them for equality.
3475    *
3476    * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
3477    * and any extension present are the same.
3478    * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
3479    * the same.
3480    * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
3481    * the same, and one NSN could be a shorter version of the other number. This includes the case
3482    * where one has an extension specified, and the other does not.
3483    * Returns NO_MATCH otherwise.
3484    * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
3485    * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
3486    *
3487    * @param firstNumberIn  first number to compare
3488    * @param secondNumberIn  second number to compare
3489    *
3490    * @return  NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
3491    *     of the two numbers, described in the method definition.
3492    */
3493   public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
3494     // We only care about the fields that uniquely define a number, so we copy these across
3495     // explicitly.
3496     PhoneNumber firstNumber = copyCoreFieldsOnly(firstNumberIn);
3497     PhoneNumber secondNumber = copyCoreFieldsOnly(secondNumberIn);
3498     // Early exit if both had extensions and these are different.
3499     if (firstNumber.hasExtension() && secondNumber.hasExtension()
3500         && !firstNumber.getExtension().equals(secondNumber.getExtension())) {
3501       return MatchType.NO_MATCH;
3502     }
3503     int firstNumberCountryCode = firstNumber.getCountryCode();
3504     int secondNumberCountryCode = secondNumber.getCountryCode();
3505     // Both had country_code specified.
3506     if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
3507       if (firstNumber.exactlySameAs(secondNumber)) {
3508         return MatchType.EXACT_MATCH;
3509       } else if (firstNumberCountryCode == secondNumberCountryCode
3510           && isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3511         // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3512         // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3513         // shorter variant of the other.
3514         return MatchType.SHORT_NSN_MATCH;
3515       }
3516       // This is not a match.
3517       return MatchType.NO_MATCH;
3518     }
3519     // Checks cases where one or both country_code fields were not specified. To make equality
3520     // checks easier, we first set the country_code fields to be equal.
3521     firstNumber.setCountryCode(secondNumberCountryCode);
3522     // If all else was the same, then this is an NSN_MATCH.
3523     if (firstNumber.exactlySameAs(secondNumber)) {
3524       return MatchType.NSN_MATCH;
3525     }
3526     if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3527       return MatchType.SHORT_NSN_MATCH;
3528     }
3529     return MatchType.NO_MATCH;
3530   }
3531 
3532   // Returns true when one national number is the suffix of the other or both are the same.
3533   private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
3534                                                    PhoneNumber secondNumber) {
3535     String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
3536     String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
3537     // Note that endsWith returns true if the numbers are equal.
3538     return firstNumberNationalNumber.endsWith(secondNumberNationalNumber)
3539         || secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
3540   }
3541 
3542   /**
3543    * Takes two phone numbers as strings and compares them for equality. This is a convenience
3544    * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3545    *
3546    * @param firstNumber  first number to compare. Can contain formatting, and can have country
3547    *     calling code specified with + at the start.
3548    * @param secondNumber  second number to compare. Can contain formatting, and can have country
3549    *     calling code specified with + at the start.
3550    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3551    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3552    */
3553   public MatchType isNumberMatch(CharSequence firstNumber, CharSequence secondNumber) {
3554     try {
3555       PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
3556       return isNumberMatch(firstNumberAsProto, secondNumber);
3557     } catch (NumberParseException e) {
3558       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3559         try {
3560           PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3561           return isNumberMatch(secondNumberAsProto, firstNumber);
3562         } catch (NumberParseException e2) {
3563           if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3564             try {
3565               PhoneNumber firstNumberProto = new PhoneNumber();
3566               PhoneNumber secondNumberProto = new PhoneNumber();
3567               parseHelper(firstNumber, null, false, false, firstNumberProto);
3568               parseHelper(secondNumber, null, false, false, secondNumberProto);
3569               return isNumberMatch(firstNumberProto, secondNumberProto);
3570             } catch (NumberParseException e3) {
3571               // Fall through and return MatchType.NOT_A_NUMBER.
3572             }
3573           }
3574         }
3575       }
3576     }
3577     // One or more of the phone numbers we are trying to match is not a viable phone number.
3578     return MatchType.NOT_A_NUMBER;
3579   }
3580 
3581   /**
3582    * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
3583    * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3584    *
3585    * @param firstNumber  first number to compare in proto buffer format
3586    * @param secondNumber  second number to compare. Can contain formatting, and can have country
3587    *     calling code specified with + at the start.
3588    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3589    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3590    */
3591   public MatchType isNumberMatch(PhoneNumber firstNumber, CharSequence secondNumber) {
3592     // First see if the second number has an implicit country calling code, by attempting to parse
3593     // it.
3594     try {
3595       PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3596       return isNumberMatch(firstNumber, secondNumberAsProto);
3597     } catch (NumberParseException e) {
3598       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3599         // The second number has no country calling code. EXACT_MATCH is no longer possible.
3600         // We parse it as if the region was the same as that for the first number, and if
3601         // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3602         String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
3603         try {
3604           if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
3605             PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
3606             MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
3607             if (match == MatchType.EXACT_MATCH) {
3608               return MatchType.NSN_MATCH;
3609             }
3610             return match;
3611           } else {
3612             // If the first number didn't have a valid country calling code, then we parse the
3613             // second number without one as well.
3614             PhoneNumber secondNumberProto = new PhoneNumber();
3615             parseHelper(secondNumber, null, false, false, secondNumberProto);
3616             return isNumberMatch(firstNumber, secondNumberProto);
3617           }
3618         } catch (NumberParseException e2) {
3619           // Fall-through to return NOT_A_NUMBER.
3620         }
3621       }
3622     }
3623     // One or more of the phone numbers we are trying to match is not a viable phone number.
3624     return MatchType.NOT_A_NUMBER;
3625   }
3626 
3627   /**
3628    * Returns true if the number can be dialled from outside the region, or unknown. If the number
3629    * can only be dialled from within the region, returns false. Does not check the number is a valid
3630    * number. Note that, at the moment, this method does not handle short numbers (which are
3631    * currently all presumed to not be diallable from outside their country).
3632    *
3633    * @param number  the phone-number for which we want to know whether it is diallable from
3634    *     outside the region
3635    */
3636   public boolean canBeInternationallyDialled(PhoneNumber number) {
3637     PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3638     if (metadata == null) {
3639       // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3640       // internationally diallable, and will be caught here.
3641       return true;
3642     }
3643     String nationalSignificantNumber = getNationalSignificantNumber(number);
3644     return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
3645   }
3646 
3647   /**
3648    * Returns true if the supplied region supports mobile number portability. Returns false for
3649    * invalid, unknown or regions that don't support mobile number portability.
3650    *
3651    * @param regionCode  the region for which we want to know whether it supports mobile number
3652    *     portability or not
3653    */
3654   public boolean isMobileNumberPortableRegion(String regionCode) {
3655     PhoneMetadata metadata = getMetadataForRegion(regionCode);
3656     if (metadata == null) {
3657       logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
3658       return false;
3659     }
3660     return metadata.getMobileNumberPortableRegion();
3661   }
3662 }
3663