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