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