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