2 * Copyright (C) 2009 The Libphonenumber Authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.i18n.phonenumbers;
19 import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
20 import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
21 import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
22 import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
23 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
24 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.ObjectInputStream;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.List;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
44 * Utility for international phone numbers. Functionality includes formatting, parsing and
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>.
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
53 * http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm
55 * @author Shaopeng Jia
58 public class PhoneNumberUtil {
59 private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName());
61 /** Flags to use when compiling regular expressions for phone numbers. */
62 static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
63 // The minimum and maximum length of the national significant number.
64 private static final int MIN_LENGTH_FOR_NSN = 2;
65 // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
66 static final int MAX_LENGTH_FOR_NSN = 16;
67 // The maximum length of the country calling code.
68 static final int MAX_LENGTH_COUNTRY_CODE = 3;
69 // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
70 // input from overflowing the regular-expression engine.
71 private static final int MAX_INPUT_STRING_LENGTH = 250;
72 static final String META_DATA_FILE_PREFIX =
73 "/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto";
75 // Region-code for the unknown region.
76 private static final String UNKNOWN_REGION = "ZZ";
78 private static final int NANPA_COUNTRY_CODE = 1;
80 // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
81 // a mobile phone in Colombia.
82 private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
84 // The PLUS_SIGN signifies the international prefix.
85 static final char PLUS_SIGN = '+';
87 private static final char STAR_SIGN = '*';
89 private static final String RFC3966_EXTN_PREFIX = ";ext=";
90 private static final String RFC3966_PREFIX = "tel:";
91 private static final String RFC3966_PHONE_CONTEXT = ";phone-context=";
92 private static final String RFC3966_ISDN_SUBADDRESS = ";isub=";
94 // A map that contains characters that are essential when dialling. That means any of the
95 // characters in this map must not be removed from a number when dialling, otherwise the call
96 // will not reach the intended destination.
97 private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
99 // Only upper-case variants of alpha characters are stored.
100 private static final Map<Character, Character> ALPHA_MAPPINGS;
102 // For performance reasons, amalgamate both into one map.
103 private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
105 // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
106 // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
107 private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
110 // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
111 // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
112 HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
113 asciiDigitMappings.put('0', '0');
114 asciiDigitMappings.put('1', '1');
115 asciiDigitMappings.put('2', '2');
116 asciiDigitMappings.put('3', '3');
117 asciiDigitMappings.put('4', '4');
118 asciiDigitMappings.put('5', '5');
119 asciiDigitMappings.put('6', '6');
120 asciiDigitMappings.put('7', '7');
121 asciiDigitMappings.put('8', '8');
122 asciiDigitMappings.put('9', '9');
124 HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
125 alphaMap.put('A', '2');
126 alphaMap.put('B', '2');
127 alphaMap.put('C', '2');
128 alphaMap.put('D', '3');
129 alphaMap.put('E', '3');
130 alphaMap.put('F', '3');
131 alphaMap.put('G', '4');
132 alphaMap.put('H', '4');
133 alphaMap.put('I', '4');
134 alphaMap.put('J', '5');
135 alphaMap.put('K', '5');
136 alphaMap.put('L', '5');
137 alphaMap.put('M', '6');
138 alphaMap.put('N', '6');
139 alphaMap.put('O', '6');
140 alphaMap.put('P', '7');
141 alphaMap.put('Q', '7');
142 alphaMap.put('R', '7');
143 alphaMap.put('S', '7');
144 alphaMap.put('T', '8');
145 alphaMap.put('U', '8');
146 alphaMap.put('V', '8');
147 alphaMap.put('W', '9');
148 alphaMap.put('X', '9');
149 alphaMap.put('Y', '9');
150 alphaMap.put('Z', '9');
151 ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
153 HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
154 combinedMap.putAll(ALPHA_MAPPINGS);
155 combinedMap.putAll(asciiDigitMappings);
156 ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
158 HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
159 diallableCharMap.putAll(asciiDigitMappings);
160 diallableCharMap.put(PLUS_SIGN, PLUS_SIGN);
161 diallableCharMap.put('*', '*');
162 DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
164 HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
165 // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
166 for (char c : ALPHA_MAPPINGS.keySet()) {
167 allPlusNumberGroupings.put(Character.toLowerCase(c), c);
168 allPlusNumberGroupings.put(c, c);
170 allPlusNumberGroupings.putAll(asciiDigitMappings);
171 // Put grouping symbols.
172 allPlusNumberGroupings.put('-', '-');
173 allPlusNumberGroupings.put('\uFF0D', '-');
174 allPlusNumberGroupings.put('\u2010', '-');
175 allPlusNumberGroupings.put('\u2011', '-');
176 allPlusNumberGroupings.put('\u2012', '-');
177 allPlusNumberGroupings.put('\u2013', '-');
178 allPlusNumberGroupings.put('\u2014', '-');
179 allPlusNumberGroupings.put('\u2015', '-');
180 allPlusNumberGroupings.put('\u2212', '-');
181 allPlusNumberGroupings.put('/', '/');
182 allPlusNumberGroupings.put('\uFF0F', '/');
183 allPlusNumberGroupings.put(' ', ' ');
184 allPlusNumberGroupings.put('\u3000', ' ');
185 allPlusNumberGroupings.put('\u2060', ' ');
186 allPlusNumberGroupings.put('.', '.');
187 allPlusNumberGroupings.put('\uFF0E', '.');
188 ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
191 // Pattern that makes it easy to distinguish whether a region has a unique international dialing
192 // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
193 // represented as a string that contains a sequence of ASCII digits. If there are multiple
194 // available international prefixes in a region, they will be represented as a regex string that
195 // always contains character(s) other than ASCII digits.
196 // Note this regex also includes tilde, which signals waiting for the tone.
197 private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
198 Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
200 // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
201 // found as a leading character only.
202 // This consists of dash characters, white space characters, full stops, slashes,
203 // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
204 // placeholder for carrier information in some phone numbers. Full-width variants are also
206 static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
207 "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
209 private static final String DIGITS = "\\p{Nd}";
210 // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
211 private static final String VALID_ALPHA =
212 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
213 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
214 static final String PLUS_CHARS = "+\uFF0B";
215 static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
216 private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
217 private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
219 // Regular expression of acceptable characters that may start a phone number for the purposes of
220 // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
221 // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
222 // does not contain alpha characters, although they may be used later in the number. It also does
223 // not include other punctuation, as this will be stripped later during parsing and is of no
224 // information value when parsing a number.
225 private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
226 private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
228 // Regular expression of characters typically used to start a second phone number for the purposes
229 // of parsing. This allows us to strip off parts of the number that are actually the start of
230 // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
231 // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
232 // extension so that the first number is parsed correctly.
233 private static final String SECOND_NUMBER_START = "[\\\\/] *x";
234 static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
236 // Regular expression of trailing characters that we want to remove. We remove all characters that
237 // are not alpha or numerical characters. The hash character is retained here, as it may signify
238 // the previous block was an extension.
239 private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
240 static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
242 // We use this pattern to check if the phone number has at least three letters in it - if so, then
243 // we treat it as a number where some phone-number digits are represented by letters.
244 private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
246 // Regular expression of viable phone numbers. This is location independent. Checks we have at
247 // least three leading digits, and only valid punctuation, alpha characters and
248 // digits in the phone number. Does not include extension data.
249 // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
250 // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
252 // Corresponds to the following:
253 // [digits]{minLengthNsn}|
254 // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
256 // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
257 // as "15" etc, but only if there is no punctuation in them. The second expression restricts the
258 // number of digits to three or more, but then allows them to be in international form, and to
259 // have alpha-characters and punctuation.
261 // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
262 private static final String VALID_PHONE_NUMBER =
263 DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" +
264 "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
265 VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
267 // Default extension prefix to use when formatting. This will be put in front of any extension
268 // component of the number, after the main national number is formatted. For example, if you wish
269 // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
270 // as the default extension prefix. This can be overridden by region-specific preferences.
271 private static final String DEFAULT_EXTN_PREFIX = " ext. ";
273 // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
275 private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
276 // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
277 // case-insensitive regexp match. Wide character versions are also provided after each ASCII
279 private static final String EXTN_PATTERNS_FOR_PARSING;
280 static final String EXTN_PATTERNS_FOR_MATCHING;
282 // One-character symbols that can be used to indicate an extension.
283 String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
284 // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
285 // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
287 String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
289 EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
290 EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
294 * Helper initialiser method to create the regular-expression pattern to match extensions,
295 * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
297 private static String createExtnPattern(String singleExtnSymbols) {
298 // There are three regular expressions here. The first covers RFC 3966 format, where the
299 // extension is added using ";ext=". The second more generic one starts with optional white
300 // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
301 // the numbers themselves. The other one covers the special case of American numbers where the
302 // extension is written with a hash at the end, such as "- 503#".
303 // Note that the only capturing groups should be around the digits that you want to capture as
304 // part of the extension, or else parsing will fail!
305 // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
306 // for representing the accented o - the character itself, and one in the unicode decomposed
307 // form with the combining acute accent.
308 return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
309 "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
310 "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
311 "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
312 "[- ]+(" + DIGITS + "{1,5})#");
315 // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
316 // digits, for use when parsing.
317 private static final Pattern EXTN_PATTERN =
318 Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
320 // We append optionally the extension pattern to the end here, as a valid phone number may
321 // have an extension prefix appended, followed by 1 or more digits.
322 private static final Pattern VALID_PHONE_NUMBER_PATTERN =
323 Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
325 static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
327 // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
328 // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
329 // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
331 private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
332 private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
333 private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
334 private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
336 // A pattern that is used to determine if the national prefix formatting rule has the first group
337 // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
338 // for unbalanced parentheses.
339 private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?");
341 private static PhoneNumberUtil instance = null;
343 public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
346 * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
347 * E123. For example, the number of the Google Switzerland office will be written as
348 * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
349 * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
350 * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
351 * separating symbols replaced with a hyphen, and with any phone number extension appended with
352 * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
354 * Note: If you are considering storing the number in a neutral format, you are highly advised to
355 * use the PhoneNumber class.
357 public enum PhoneNumberFormat {
365 * Type of phone numbers.
367 public enum PhoneNumberType {
370 // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
371 // mobile numbers by looking at the phone number itself.
372 FIXED_LINE_OR_MOBILE,
376 // The cost of this call is shared between the caller and the recipient, and is hence typically
377 // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
380 // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
382 // A personal number is associated with a particular person, and may be routed to either a
383 // MOBILE or FIXED_LINE number. Some more information can be found here:
384 // http://en.wikipedia.org/wiki/Personal_Numbers
387 // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
388 // specific offices, but allow one number to be used for a company.
390 // Used for "Voice Mail Access Numbers".
392 // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
398 * Types of phone number matches. See detailed description beside the isNumberMatch() method.
400 public enum MatchType {
409 * Possible outcomes when testing if a PhoneNumber is possible.
411 public enum ValidationResult {
413 INVALID_COUNTRY_CODE,
419 * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
420 * segments. The levels here are ordered in increasing strictness.
422 public enum Leniency {
424 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
425 * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
429 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
430 return util.isPossibleNumber(number);
434 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
435 * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
436 * in national format must have their national-prefix present if it is usually written for a
437 * number of this type.
441 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
442 if (!util.isValidNumber(number) ||
443 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) {
446 return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util);
450 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
451 * are grouped in a possible way for this locale. For example, a US number written as
452 * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
453 * "650 253 0000", "650 2530000" or "6502530000" are.
454 * Numbers with more than one '/' symbol in the national significant number are also dropped at
457 * Warning: This level might result in lower coverage especially for regions outside of country
458 * code "+1". If you are not sure about which level to use, email the discussion group
459 * libphonenumber-discuss@googlegroups.com.
463 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
464 if (!util.isValidNumber(number) ||
465 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
466 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
467 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
470 return PhoneNumberMatcher.checkNumberGroupingIsValid(
471 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
472 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
473 StringBuilder normalizedCandidate,
474 String[] expectedNumberGroups) {
475 return PhoneNumberMatcher.allNumberGroupsRemainGrouped(
476 util, number, normalizedCandidate, expectedNumberGroups);
482 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
483 * are grouped in the same way that we would have formatted it, or as a single block. For
484 * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
485 * "650 253 0000" or "6502530000" are.
486 * Numbers with more than one '/' symbol are also dropped at this level.
488 * Warning: This level might result in lower coverage especially for regions outside of country
489 * code "+1". If you are not sure about which level to use, email the discussion group
490 * libphonenumber-discuss@googlegroups.com.
494 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
495 if (!util.isValidNumber(number) ||
496 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
497 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
498 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
501 return PhoneNumberMatcher.checkNumberGroupingIsValid(
502 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
503 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
504 StringBuilder normalizedCandidate,
505 String[] expectedNumberGroups) {
506 return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent(
507 util, number, normalizedCandidate, expectedNumberGroups);
513 /** Returns true if {@code number} is a verified number according to this leniency. */
514 abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
517 // A mapping from a country calling code to the region codes which denote the region represented
518 // by that country calling code. In the case of multiple regions sharing a calling code, such as
519 // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
521 private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap;
523 // The set of regions that share country calling code 1.
524 // There are roughly 26 regions and we set the initial capacity of the HashSet to 35 to offer a
525 // load factor of roughly 0.75.
526 private final Set<String> nanpaRegions = new HashSet<String>(35);
528 // A mapping from a region code to the PhoneMetadata for that region.
529 // Note: Synchronization, though only needed for the Android version of the library, is used in
530 // all versions for consistency.
531 private final Map<String, PhoneMetadata> regionToMetadataMap =
532 Collections.synchronizedMap(new HashMap<String, PhoneMetadata>());
534 // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
535 // that country calling code. Examples of the country calling codes include 800 (International
536 // Toll Free Service) and 808 (International Shared Cost Service).
537 // Note: Synchronization, though only needed for the Android version of the library, is used in
538 // all versions for consistency.
539 private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
540 Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>());
542 // A cache for frequently used region-specific regular expressions.
543 // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on
544 // performance measurements.
545 private final RegexCache regexCache = new RegexCache(100);
547 // The set of regions the library supports.
548 // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
549 // load factor of roughly 0.75.
550 private final Set<String> supportedRegions = new HashSet<String>(320);
552 // The set of county calling codes that map to the non-geo entity region ("001"). This set
553 // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
554 private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>();
556 // The prefix of the metadata files from which region data is loaded.
557 private final String currentFilePrefix;
560 * This class implements a singleton, so the only constructor is private.
562 private PhoneNumberUtil(String filePrefix,
563 Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
564 this.currentFilePrefix = filePrefix;
565 this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
566 for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) {
567 List<String> regionCodes = entry.getValue();
568 // We can assume that if the county calling code maps to the non-geo entity region code then
569 // that's the only region code it maps to.
570 if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) {
571 // This is the subset of all country codes that map to the non-geo entity region code.
572 countryCodesForNonGeographicalRegion.add(entry.getKey());
574 // The supported regions set does not include the "001" non-geo entity region code.
575 supportedRegions.addAll(regionCodes);
578 // If the non-geo entity still got added to the set of supported regions it must be because
579 // there are entries that list the non-geo entity alongside normal regions (which is wrong).
580 // If we discover this, remove the non-geo entity from the set of supported regions and log.
581 if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) {
582 logger.log(Level.WARNING, "invalid metadata " +
583 "(country calling code was mapped to the non-geo entity as well as specific region(s))");
585 nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
588 // @VisibleForTesting
589 void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode) {
590 boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
591 String fileName = filePrefix + "_" +
592 (isNonGeoRegion ? String.valueOf(countryCallingCode) : regionCode);
593 InputStream source = PhoneNumberUtil.class.getResourceAsStream(fileName);
594 if (source == null) {
595 logger.log(Level.SEVERE, "missing metadata: " + fileName);
596 throw new IllegalStateException("missing metadata: " + fileName);
598 ObjectInputStream in = null;
600 in = new ObjectInputStream(source);
601 PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
602 metadataCollection.readExternal(in);
603 List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
604 if (metadataList.isEmpty()) {
605 logger.log(Level.SEVERE, "empty metadata: " + fileName);
606 throw new IllegalStateException("empty metadata: " + fileName);
608 if (metadataList.size() > 1) {
609 logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName);
611 PhoneMetadata metadata = metadataList.get(0);
612 if (isNonGeoRegion) {
613 countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);
615 regionToMetadataMap.put(regionCode, metadata);
617 } catch (IOException e) {
618 logger.log(Level.SEVERE, "cannot load/parse metadata: " + fileName, e);
619 throw new RuntimeException("cannot load/parse metadata: " + fileName, e);
625 private static void close(InputStream in) {
629 } catch (IOException e) {
630 logger.log(Level.WARNING, "error closing input stream (ignored)", e);
636 * Attempts to extract a possible number from the string passed in. This currently strips all
637 * leading characters that cannot be used to start a phone number. Characters that can be used to
638 * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
639 * are found in the number passed in, an empty string is returned. This function also attempts to
640 * strip off any alternative extensions or endings if two or more are present, such as in the case
641 * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
642 * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
643 * number is parsed correctly.
645 * @param number the string that might contain a phone number
646 * @return the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
647 * string if no character used to start phone numbers (such as + or any digit) is
648 * found in the number
650 static String extractPossibleNumber(String number) {
651 Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
653 number = number.substring(m.start());
654 // Remove trailing non-alpha non-numerical characters.
655 Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
656 if (trailingCharsMatcher.find()) {
657 number = number.substring(0, trailingCharsMatcher.start());
658 logger.log(Level.FINER, "Stripped trailing characters: " + number);
660 // Check for extra numbers at the end.
661 Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
662 if (secondNumber.find()) {
663 number = number.substring(0, secondNumber.start());
672 * Checks to see if the string of characters could possibly be a phone number at all. At the
673 * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
674 * commonly found in phone numbers.
675 * This method does not require the number to be normalized in advance - but does assume that
676 * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
678 * @param number string to be checked for viability as a phone number
679 * @return true if the number could be a phone number of some sort, otherwise false
681 // @VisibleForTesting
682 static boolean isViablePhoneNumber(String number) {
683 if (number.length() < MIN_LENGTH_FOR_NSN) {
686 Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
691 * Normalizes a string of characters representing a phone number. This performs the following
693 * Punctuation is stripped.
694 * For ALPHA/VANITY numbers:
695 * Letters are converted to their numeric representation on a telephone keypad. The keypad
696 * used here is the one defined in ITU Recommendation E.161. This is only done if there are
697 * 3 or more letters in the number, to lessen the risk that such letters are typos.
699 * Wide-ascii digits are converted to normal ASCII (European) digits.
700 * Arabic-Indic numerals are converted to European numerals.
701 * Spurious alpha characters are stripped.
703 * @param number a string of characters representing a phone number
704 * @return the normalized string version of the phone number
706 static String normalize(String number) {
707 Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
709 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
711 return normalizeDigitsOnly(number);
716 * Normalizes a string of characters representing a phone number. This is a wrapper for
717 * normalize(String number) but does in-place normalization of the StringBuilder provided.
719 * @param number a StringBuilder of characters representing a phone number that will be
720 * normalized in place
722 static void normalize(StringBuilder number) {
723 String normalizedNumber = normalize(number.toString());
724 number.replace(0, number.length(), normalizedNumber);
728 * Normalizes a string of characters representing a phone number. This converts wide-ascii and
729 * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
731 * @param number a string of characters representing a phone number
732 * @return the normalized string version of the phone number
734 public static String normalizeDigitsOnly(String number) {
735 return normalizeDigits(number, false /* strip non-digits */).toString();
738 static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
739 StringBuilder normalizedDigits = new StringBuilder(number.length());
740 for (char c : number.toCharArray()) {
741 int digit = Character.digit(c, 10);
743 normalizedDigits.append(digit);
744 } else if (keepNonDigits) {
745 normalizedDigits.append(c);
748 return normalizedDigits;
752 * Normalizes a string of characters representing a phone number. This strips all characters which
753 * are not diallable on a mobile phone keypad (including all non-ASCII digits).
755 * @param number a string of characters representing a phone number
756 * @return the normalized string version of the phone number
758 static String normalizeDiallableCharsOnly(String number) {
759 return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
763 * Converts all alpha characters in a number to their respective digits on a keypad, but retains
764 * existing formatting.
766 public static String convertAlphaCharactersInNumber(String number) {
767 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
771 * Gets the length of the geographical area code from the {@code nationalNumber_} field of the
772 * PhoneNumber object passed in, so that clients could use it to split a national significant
773 * number into geographical area code and subscriber number. It works in such a way that the
774 * resultant subscriber number should be diallable, at least on some devices. An example of how
775 * this could be used:
778 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
779 * PhoneNumber number = phoneUtil.parse("16502530000", "US");
780 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
782 * String subscriberNumber;
784 * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
785 * if (areaCodeLength > 0) {
786 * areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
787 * subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
790 * subscriberNumber = nationalSignificantNumber;
794 * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
795 * using it for most purposes, but recommends using the more general {@code national_number}
796 * instead. Read the following carefully before deciding to use this method:
798 * <li> geographical area codes change over time, and this method honors those changes;
799 * therefore, it doesn't guarantee the stability of the result it produces.
800 * <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
801 * typically requires the full national_number to be dialled in most regions).
802 * <li> most non-geographical numbers have no area codes, including numbers from non-geographical
804 * <li> some geographical numbers have no area codes.
806 * @param number the PhoneNumber object for which clients want to know the length of the area
808 * @return the length of area code of the PhoneNumber object passed in.
810 public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
811 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
812 if (metadata == null) {
815 // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
816 // zero, we assume it is a closed dialling plan with no area codes.
817 if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) {
821 if (!isNumberGeographical(number)) {
825 return getLengthOfNationalDestinationCode(number);
829 * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in,
830 * so that clients could use it to split a national significant number into NDC and subscriber
831 * number. The NDC of a phone number is normally the first group of digit(s) right after the
832 * country calling code when the number is formatted in the international format, if there is a
833 * subscriber number part that follows. An example of how this could be used:
836 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
837 * PhoneNumber number = phoneUtil.parse("18002530000", "US");
838 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
839 * String nationalDestinationCode;
840 * String subscriberNumber;
842 * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
843 * if (nationalDestinationCodeLength > 0) {
844 * nationalDestinationCode = nationalSignificantNumber.substring(0,
845 * nationalDestinationCodeLength);
846 * subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
848 * nationalDestinationCode = "";
849 * subscriberNumber = nationalSignificantNumber;
853 * Refer to the unittests to see the difference between this function and
854 * {@link #getLengthOfGeographicalAreaCode}.
856 * @param number the PhoneNumber object for which clients want to know the length of the NDC.
857 * @return the length of NDC of the PhoneNumber object passed in.
859 public int getLengthOfNationalDestinationCode(PhoneNumber number) {
860 PhoneNumber copiedProto;
861 if (number.hasExtension()) {
862 // We don't want to alter the proto given to us, but we don't want to include the extension
863 // when we format it, so we copy it and clear the extension here.
864 copiedProto = new PhoneNumber();
865 copiedProto.mergeFrom(number);
866 copiedProto.clearExtension();
868 copiedProto = number;
871 String nationalSignificantNumber = format(copiedProto,
872 PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
873 String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
874 // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
875 // string (before the + symbol) and the second group will be the country calling code. The third
876 // group will be area code if it is not the last group.
877 if (numberGroups.length <= 3) {
881 if (getRegionCodeForCountryCode(number.getCountryCode()).equals("AR") &&
882 getNumberType(number) == PhoneNumberType.MOBILE) {
883 // Argentinian mobile numbers, when formatted in the international format, are in the form of
884 // +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and add 1 for
885 // the digit 9, which also forms part of the national significant number.
887 // TODO: Investigate the possibility of better modeling the metadata to make it
888 // easier to obtain the NDC.
889 return numberGroups[3].length() + 1;
891 return numberGroups[2].length();
895 * Normalizes a string of characters representing a phone number by replacing all characters found
896 * in the accompanying map with the values therein, and stripping all other characters if
897 * removeNonMatches is true.
899 * @param number a string of characters representing a phone number
900 * @param normalizationReplacements a mapping of characters to what they should be replaced by in
901 * the normalized version of the phone number
902 * @param removeNonMatches indicates whether characters that are not able to be replaced
903 * should be stripped from the number. If this is false, they
904 * will be left unchanged in the number.
905 * @return the normalized string version of the phone number
907 private static String normalizeHelper(String number,
908 Map<Character, Character> normalizationReplacements,
909 boolean removeNonMatches) {
910 StringBuilder normalizedNumber = new StringBuilder(number.length());
911 for (int i = 0; i < number.length(); i++) {
912 char character = number.charAt(i);
913 Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
914 if (newDigit != null) {
915 normalizedNumber.append(newDigit);
916 } else if (!removeNonMatches) {
917 normalizedNumber.append(character);
919 // If neither of the above are true, we remove this character.
921 return normalizedNumber.toString();
925 * An unsafe version of getInstance() which must only be used for testing purposes.
927 // @VisibleForTesting
928 static synchronized PhoneNumberUtil getInstance(
929 String baseFileLocation,
930 Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
931 if (instance != null) {
932 throw new IllegalStateException(
933 "PhoneNumberUtil instance is already set (you should call resetInstance() first)");
935 instance = new PhoneNumberUtil(baseFileLocation, countryCallingCodeToRegionCodeMap);
940 * Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
942 // @VisibleForTesting
943 static synchronized void resetInstance() {
948 * Convenience method to get a list of what regions the library has metadata for.
950 public Set<String> getSupportedRegions() {
951 return Collections.unmodifiableSet(supportedRegions);
955 * Convenience method to get a list of what global network calling codes the library has metadata
958 public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
959 return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion);
963 * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
964 * parsing, or validation. The instance is loaded with phone number metadata for a number of most
965 * commonly used regions.
967 * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
968 * multiple times will only result in one instance being created.
970 * @return a PhoneNumberUtil instance
972 public static synchronized PhoneNumberUtil getInstance() {
973 if (instance == null) {
974 return getInstance(META_DATA_FILE_PREFIX,
975 CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
981 * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
982 * does not start with the national prefix.
984 static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) {
985 return nationalPrefixFormattingRule.length() == 0 ||
986 FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches();
990 * Tests whether a phone number has a geographical association. It checks if the number is
991 * associated to a certain region in the country where it belongs to. Note that this doesn't
992 * verify if the number is actually in use.
994 boolean isNumberGeographical(PhoneNumber phoneNumber) {
995 PhoneNumberType numberType = getNumberType(phoneNumber);
996 // TODO: Include mobile phone numbers from countries like Indonesia, which has some
997 // mobile numbers that are geographical.
998 return numberType == PhoneNumberType.FIXED_LINE ||
999 numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
1003 * Helper function to check region code is not unknown or null.
1005 private boolean isValidRegionCode(String regionCode) {
1006 return regionCode != null && supportedRegions.contains(regionCode);
1010 * Helper function to check the country calling code is valid.
1012 private boolean hasValidCountryCallingCode(int countryCallingCode) {
1013 return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
1017 * Formats a phone number in the specified format using default rules. Note that this does not
1018 * promise to produce a phone number that the user can dial from where they are - although we do
1019 * format in either 'national' or 'international' format depending on what the client asks for, we
1020 * do not currently support a more abbreviated format, such as for users in the same "area" who
1021 * could potentially dial the number without area code. Note that if the phone number has a
1022 * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1023 * which formatting rules to apply so we return the national significant number with no formatting
1026 * @param number the phone number to be formatted
1027 * @param numberFormat the format the phone number should be formatted into
1028 * @return the formatted phone number
1030 public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
1031 if (number.getNationalNumber() == 0 && number.hasRawInput()) {
1032 // Unparseable numbers that kept their raw input just use that.
1033 // This is the only case where a number can be formatted as E164 without a
1034 // leading '+' symbol (but the original number wasn't parseable anyway).
1035 // TODO: Consider removing the 'if' above so that unparseable
1036 // strings without raw input format to the empty string instead of "+00"
1037 String rawInput = number.getRawInput();
1038 if (rawInput.length() > 0) {
1042 StringBuilder formattedNumber = new StringBuilder(20);
1043 format(number, numberFormat, formattedNumber);
1044 return formattedNumber.toString();
1048 * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
1049 * a parameter to decrease object creation when invoked many times.
1051 public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1052 StringBuilder formattedNumber) {
1053 // Clear the StringBuilder first.
1054 formattedNumber.setLength(0);
1055 int countryCallingCode = number.getCountryCode();
1056 String nationalSignificantNumber = getNationalSignificantNumber(number);
1057 if (numberFormat == PhoneNumberFormat.E164) {
1058 // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1059 // of the national number needs to be applied. Extensions are not formatted.
1060 formattedNumber.append(nationalSignificantNumber);
1061 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1065 if (!hasValidCountryCallingCode(countryCallingCode)) {
1066 formattedNumber.append(nationalSignificantNumber);
1069 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1070 // share a country calling code is contained by only one region for performance reasons. For
1071 // example, for NANPA regions it will be contained in the metadata for US.
1072 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1073 // Metadata cannot be null because the country calling code is valid (which means that the
1074 // region code cannot be ZZ and must be one of our supported region codes).
1075 PhoneMetadata metadata =
1076 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1077 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1078 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1079 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1083 * Formats a phone number in the specified format using client-defined formatting rules. Note that
1084 * if the phone number has a country calling code of zero or an otherwise invalid country calling
1085 * code, we cannot work out things like whether there should be a national prefix applied, or how
1086 * to format extensions, so we return the national significant number with no formatting applied.
1088 * @param number the phone number to be formatted
1089 * @param numberFormat the format the phone number should be formatted into
1090 * @param userDefinedFormats formatting rules specified by clients
1091 * @return the formatted phone number
1093 public String formatByPattern(PhoneNumber number,
1094 PhoneNumberFormat numberFormat,
1095 List<NumberFormat> userDefinedFormats) {
1096 int countryCallingCode = number.getCountryCode();
1097 String nationalSignificantNumber = getNationalSignificantNumber(number);
1098 if (!hasValidCountryCallingCode(countryCallingCode)) {
1099 return nationalSignificantNumber;
1101 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1102 // share a country calling code is contained by only one region for performance reasons. For
1103 // example, for NANPA regions it will be contained in the metadata for US.
1104 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1105 // Metadata cannot be null because the country calling code is valid
1106 PhoneMetadata metadata =
1107 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1109 StringBuilder formattedNumber = new StringBuilder(20);
1111 NumberFormat formattingPattern =
1112 chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1113 if (formattingPattern == null) {
1114 // If no pattern above is matched, we format the number as a whole.
1115 formattedNumber.append(nationalSignificantNumber);
1117 NumberFormat numFormatCopy = new NumberFormat();
1118 // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1119 // need to copy the rule so that subsequent replacements for different numbers have the
1120 // appropriate national prefix.
1121 numFormatCopy.mergeFrom(formattingPattern);
1122 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1123 if (nationalPrefixFormattingRule.length() > 0) {
1124 String nationalPrefix = metadata.getNationalPrefix();
1125 if (nationalPrefix.length() > 0) {
1126 // Replace $NP with national prefix and $FG with the first group ($1).
1127 nationalPrefixFormattingRule =
1128 NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
1129 nationalPrefixFormattingRule =
1130 FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
1131 numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1133 // We don't want to have a rule for how to format the national prefix if there isn't one.
1134 numFormatCopy.clearNationalPrefixFormattingRule();
1137 formattedNumber.append(
1138 formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
1140 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1141 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1142 return formattedNumber.toString();
1146 * Formats a phone number in national format for dialing using the carrier as specified in the
1147 * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1148 * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1149 * contains an empty string, returns the number in national format without any carrier code.
1151 * @param number the phone number to be formatted
1152 * @param carrierCode the carrier selection code to be used
1153 * @return the formatted phone number in national format for dialing using the carrier as
1154 * specified in the {@code carrierCode}
1156 public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
1157 int countryCallingCode = number.getCountryCode();
1158 String nationalSignificantNumber = getNationalSignificantNumber(number);
1159 if (!hasValidCountryCallingCode(countryCallingCode)) {
1160 return nationalSignificantNumber;
1163 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1164 // share a country calling code is contained by only one region for performance reasons. For
1165 // example, for NANPA regions it will be contained in the metadata for US.
1166 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1167 // Metadata cannot be null because the country calling code is valid.
1168 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1170 StringBuilder formattedNumber = new StringBuilder(20);
1171 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1172 PhoneNumberFormat.NATIONAL, carrierCode));
1173 maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1174 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1176 return formattedNumber.toString();
1179 private PhoneMetadata getMetadataForRegionOrCallingCode(
1180 int countryCallingCode, String regionCode) {
1181 return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1182 ? getMetadataForNonGeographicalRegion(countryCallingCode)
1183 : getMetadataForRegion(regionCode);
1187 * Formats a phone number in national format for dialing using the carrier as specified in the
1188 * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1189 * use the {@code fallbackCarrierCode} passed in instead. If there is no
1190 * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1191 * string, return the number in national format without any carrier code.
1193 * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1194 * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
1196 * @param number the phone number to be formatted
1197 * @param fallbackCarrierCode the carrier selection code to be used, if none is found in the
1198 * phone number itself
1199 * @return the formatted phone number in national format for dialing using the number's
1200 * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1203 public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
1204 String fallbackCarrierCode) {
1205 return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
1206 ? number.getPreferredDomesticCarrierCode()
1207 : fallbackCarrierCode);
1211 * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1212 * specific region. If the number cannot be reached from the region (e.g. some countries block
1213 * toll-free numbers from being called outside of the country), the method returns an empty
1216 * @param number the phone number to be formatted
1217 * @param regionCallingFrom the region where the call is being placed
1218 * @param withFormatting whether the number should be returned with formatting symbols, such as
1219 * spaces and dashes.
1220 * @return the formatted phone number
1222 public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1223 boolean withFormatting) {
1224 int countryCallingCode = number.getCountryCode();
1225 if (!hasValidCountryCallingCode(countryCallingCode)) {
1226 return number.hasRawInput() ? number.getRawInput() : "";
1229 String formattedNumber = "";
1230 // Clear the extension, as that part cannot normally be dialed together with the main number.
1231 PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1232 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1233 if (regionCallingFrom.equals(regionCode)) {
1234 PhoneNumberType numberType = getNumberType(numberNoExt);
1235 boolean isFixedLineOrMobile =
1236 (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
1237 (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1238 // Carrier codes may be needed in some countries. We handle this here.
1239 if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
1241 formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
1242 } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
1243 formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
1244 ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1245 // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1246 // called within Brazil. Without that, most of the carriers won't connect the call.
1247 // Because of that, we return an empty string here.
1249 } else if (regionCode.equals("HU")) {
1250 // The national format for HU numbers doesn't contain the national prefix, because that is
1251 // how numbers are normally written down. However, the national prefix is obligatory when
1252 // dialing from a mobile phone. As a result, we add it back here.
1254 getNddPrefixForRegion(regionCode, true /* strip non-digits */) +
1255 " " + format(numberNoExt, PhoneNumberFormat.NATIONAL);
1257 // For NANPA countries, non-geographical countries, Mexican and Chilean fixed line and
1258 // mobile numbers, we output international format for numbers that can be dialed
1259 // internationally as that always works.
1260 if ((countryCallingCode == NANPA_COUNTRY_CODE ||
1261 regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
1262 // MX fixed line and mobile numbers should always be formatted in international format,
1263 // even when dialed within MX. For national format to work, a carrier code needs to be
1264 // used, and the correct carrier code depends on if the caller and callee are from the
1265 // same local area. It is trickier to get that to work correctly than using
1266 // international format, which is tested to work fine on all carriers.
1267 // CL fixed line numbers need the national prefix when dialing in the national format,
1268 // but don't have it when used for display. The reverse is true for mobile numbers.
1269 // As a result, we output them in the international format to make it work.
1270 ((regionCode.equals("MX") || regionCode.equals("CL")) && isFixedLineOrMobile)) &&
1271 canBeInternationallyDialled(numberNoExt)) {
1272 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1274 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1277 } else if (canBeInternationallyDialled(numberNoExt)) {
1278 return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1279 : format(numberNoExt, PhoneNumberFormat.E164);
1281 return withFormatting ? formattedNumber
1282 : normalizeDiallableCharsOnly(formattedNumber);
1286 * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1287 * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1288 * same as that of the region where the number is from, then NATIONAL formatting will be applied.
1290 * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1291 * calling code, then we return the number with no formatting applied.
1293 * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1294 * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1295 * is used. For regions which have multiple international prefixes, the number in its
1296 * INTERNATIONAL format will be returned instead.
1298 * @param number the phone number to be formatted
1299 * @param regionCallingFrom the region where the call is being placed
1300 * @return the formatted phone number
1302 public String formatOutOfCountryCallingNumber(PhoneNumber number,
1303 String regionCallingFrom) {
1304 if (!isValidRegionCode(regionCallingFrom)) {
1305 logger.log(Level.WARNING,
1306 "Trying to format number from invalid region "
1308 + ". International formatting applied.");
1309 return format(number, PhoneNumberFormat.INTERNATIONAL);
1311 int countryCallingCode = number.getCountryCode();
1312 String nationalSignificantNumber = getNationalSignificantNumber(number);
1313 if (!hasValidCountryCallingCode(countryCallingCode)) {
1314 return nationalSignificantNumber;
1316 if (countryCallingCode == NANPA_COUNTRY_CODE) {
1317 if (isNANPACountry(regionCallingFrom)) {
1318 // For NANPA regions, return the national format for these regions but prefix it with the
1319 // country calling code.
1320 return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
1322 } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1323 // If regions share a country calling code, the country calling code need not be dialled.
1324 // This also applies when dialling within a region, so this if clause covers both these cases.
1325 // Technically this is the case for dialling from La Reunion to other overseas departments of
1326 // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
1327 // edge case for now and for those cases return the version including country calling code.
1328 // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
1329 return format(number, PhoneNumberFormat.NATIONAL);
1331 // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1332 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1333 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1335 // For regions that have multiple international prefixes, the international format of the
1336 // number is returned, unless there is a preferred international prefix.
1337 String internationalPrefixForFormatting = "";
1338 if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
1339 internationalPrefixForFormatting = internationalPrefix;
1340 } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1341 internationalPrefixForFormatting =
1342 metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1345 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1346 // Metadata cannot be null because the country calling code is valid.
1347 PhoneMetadata metadataForRegion =
1348 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1349 String formattedNationalNumber =
1350 formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1351 StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1352 maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1354 if (internationalPrefixForFormatting.length() > 0) {
1355 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1356 .insert(0, internationalPrefixForFormatting);
1358 prefixNumberWithCountryCallingCode(countryCallingCode,
1359 PhoneNumberFormat.INTERNATIONAL,
1362 return formattedNumber.toString();
1366 * Formats a phone number using the original phone number format that the number is parsed from.
1367 * The original format is embedded in the country_code_source field of the PhoneNumber object
1368 * passed in. If such information is missing, the number will be formatted into the NATIONAL
1369 * format by default. When the number contains a leading zero and this is unexpected for this
1370 * country, or we don't have a formatting pattern for the number, the method returns the raw input
1371 * when it is available.
1373 * Note this method guarantees no digit will be inserted, removed or modified as a result of
1376 * @param number the phone number that needs to be formatted in its original number format
1377 * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number
1379 * @return the formatted phone number in its original number format
1381 public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
1382 if (number.hasRawInput() &&
1383 (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
1384 // We check if we have the formatting pattern because without that, we might format the number
1385 // as a group without national prefix.
1386 return number.getRawInput();
1388 if (!number.hasCountryCodeSource()) {
1389 return format(number, PhoneNumberFormat.NATIONAL);
1391 String formattedNumber;
1392 switch (number.getCountryCodeSource()) {
1393 case FROM_NUMBER_WITH_PLUS_SIGN:
1394 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1396 case FROM_NUMBER_WITH_IDD:
1397 formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1399 case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1400 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1402 case FROM_DEFAULT_COUNTRY:
1403 // Fall-through to default case.
1405 String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1406 // We strip non-digits from the NDD here, and from the raw input later, so that we can
1407 // compare them easily.
1408 String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1409 String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1410 if (nationalPrefix == null || nationalPrefix.length() == 0) {
1411 // If the region doesn't have a national prefix at all, we can safely return the national
1412 // format without worrying about a national prefix being added.
1413 formattedNumber = nationalFormat;
1416 // Otherwise, we check if the original number was entered with a national prefix.
1417 if (rawInputContainsNationalPrefix(
1418 number.getRawInput(), nationalPrefix, regionCode)) {
1419 // If so, we can safely return the national format.
1420 formattedNumber = nationalFormat;
1423 // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1424 // there is no metadata for the region.
1425 PhoneMetadata metadata = getMetadataForRegion(regionCode);
1426 String nationalNumber = getNationalSignificantNumber(number);
1427 NumberFormat formatRule =
1428 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1429 // The format rule could still be null here if the national number was 0 and there was no
1430 // raw input (this should not be possible for numbers generated by the phonenumber library
1431 // as they would also not have a country calling code and we would have exited earlier).
1432 if (formatRule == null) {
1433 formattedNumber = nationalFormat;
1436 // When the format we apply to this number doesn't contain national prefix, we can just
1437 // return the national format.
1438 // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
1439 String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1440 // We assume that the first-group symbol will never be _before_ the national prefix.
1441 int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1442 if (indexOfFirstGroup <= 0) {
1443 formattedNumber = nationalFormat;
1446 candidateNationalPrefixRule =
1447 candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1448 candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1449 if (candidateNationalPrefixRule.length() == 0) {
1450 // National prefix not used when formatting this number.
1451 formattedNumber = nationalFormat;
1454 // Otherwise, we need to remove the national prefix from our output.
1455 NumberFormat numFormatCopy = new NumberFormat();
1456 numFormatCopy.mergeFrom(formatRule);
1457 numFormatCopy.clearNationalPrefixFormattingRule();
1458 List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
1459 numberFormats.add(numFormatCopy);
1460 formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1463 String rawInput = number.getRawInput();
1464 // If no digit is inserted/removed/modified as a result of our formatting, we return the
1465 // formatted phone number; otherwise we return the raw input the user entered.
1466 if (formattedNumber != null && rawInput.length() > 0) {
1467 String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1468 String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1469 if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1470 formattedNumber = rawInput;
1473 return formattedNumber;
1476 // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1477 // national prefix is assumed to be in digits-only form.
1478 private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1479 String regionCode) {
1480 String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1481 if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1483 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1484 // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1485 // check the validity of the number if the assumed national prefix is removed (777123 won't
1486 // be valid in Japan).
1487 return isValidNumber(
1488 parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1489 } catch (NumberParseException e) {
1497 * Returns true if a number is from a region whose national significant number couldn't contain a
1498 * leading zero, but has the italian_leading_zero field set to true.
1500 private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
1501 return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
1504 private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1505 int countryCallingCode = number.getCountryCode();
1506 String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1507 PhoneMetadata metadata =
1508 getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
1509 if (metadata == null) {
1512 String nationalNumber = getNationalSignificantNumber(number);
1513 NumberFormat formatRule =
1514 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1515 return formatRule != null;
1519 * Formats a phone number for out-of-country dialing purposes.
1521 * Note that in this version, if the number was entered originally using alpha characters and
1522 * this version of the number is stored in raw_input, this representation of the number will be
1523 * used rather than the digit representation. Grouping information, as specified by characters
1524 * such as "-" and " ", will be retained.
1526 * <p><b>Caveats:</b></p>
1528 * <li> This will not produce good results if the country calling code is both present in the raw
1529 * input _and_ is the start of the national number. This is not a problem in the regions
1530 * which typically use alpha numbers.
1531 * <li> This will also not produce good results if the raw input has any grouping information
1532 * within the first three digits of the national number, and if the function needs to strip
1533 * preceding digits/words in the raw input before these digits. Normally people group the
1534 * first three digits together so this is not a huge problem - and will be fixed if it
1538 * @param number the phone number that needs to be formatted
1539 * @param regionCallingFrom the region where the call is being placed
1540 * @return the formatted phone number
1542 public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1543 String regionCallingFrom) {
1544 String rawInput = number.getRawInput();
1545 // If there is no raw input, then we can't keep alpha characters because there aren't any.
1546 // In this case, we return formatOutOfCountryCallingNumber.
1547 if (rawInput.length() == 0) {
1548 return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1550 int countryCode = number.getCountryCode();
1551 if (!hasValidCountryCallingCode(countryCode)) {
1554 // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1555 // the number in raw_input with the parsed number.
1556 // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1558 rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1559 // Now we trim everything before the first three digits in the parsed number. We choose three
1560 // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1561 // trim anything at all. Similarly, if the national number was less than three digits, we don't
1562 // trim anything at all.
1563 String nationalNumber = getNationalSignificantNumber(number);
1564 if (nationalNumber.length() > 3) {
1565 int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1566 if (firstNationalNumberDigit != -1) {
1567 rawInput = rawInput.substring(firstNationalNumberDigit);
1570 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1571 if (countryCode == NANPA_COUNTRY_CODE) {
1572 if (isNANPACountry(regionCallingFrom)) {
1573 return countryCode + " " + rawInput;
1575 } else if (metadataForRegionCallingFrom != null &&
1576 countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1577 NumberFormat formattingPattern =
1578 chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
1580 if (formattingPattern == null) {
1581 // If no pattern above is matched, we format the original input.
1584 NumberFormat newFormat = new NumberFormat();
1585 newFormat.mergeFrom(formattingPattern);
1586 // The first group is the first group of digits that the user wrote together.
1587 newFormat.setPattern("(\\d+)(.*)");
1588 // Here we just concatenate them back together after the national prefix has been fixed.
1589 newFormat.setFormat("$1$2");
1590 // Now we format using this pattern instead of the default pattern, but with the national
1591 // prefix prefixed if necessary.
1592 // This will not work in the cases where the pattern (and not the leading digits) decide
1593 // whether a national prefix needs to be used, since we have overridden the pattern to match
1594 // anything, but that is not the case in the metadata to date.
1595 return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
1597 String internationalPrefixForFormatting = "";
1598 // If an unsupported region-calling-from is entered, or a country with multiple international
1599 // prefixes, the international format of the number is returned, unless there is a preferred
1600 // international prefix.
1601 if (metadataForRegionCallingFrom != null) {
1602 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1603 internationalPrefixForFormatting =
1604 UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1605 ? internationalPrefix
1606 : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1608 StringBuilder formattedNumber = new StringBuilder(rawInput);
1609 String regionCode = getRegionCodeForCountryCode(countryCode);
1610 // Metadata cannot be null because the country calling code is valid.
1611 PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1612 maybeAppendFormattedExtension(number, metadataForRegion,
1613 PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1614 if (internationalPrefixForFormatting.length() > 0) {
1615 formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1616 .insert(0, internationalPrefixForFormatting);
1618 // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1619 // region chosen has multiple international dialling prefixes.
1620 logger.log(Level.WARNING,
1621 "Trying to format number from invalid region "
1623 + ". International formatting applied.");
1624 prefixNumberWithCountryCallingCode(countryCode,
1625 PhoneNumberFormat.INTERNATIONAL,
1628 return formattedNumber.toString();
1632 * Gets the national significant number of the a phone number. Note a national significant number
1633 * doesn't contain a national prefix or any formatting.
1635 * @param number the phone number for which the national significant number is needed
1636 * @return the national significant number of the PhoneNumber object passed in
1638 public String getNationalSignificantNumber(PhoneNumber number) {
1639 // If a leading zero has been set, we prefix this now. Note this is not a national prefix.
1640 StringBuilder nationalNumber = new StringBuilder(number.isItalianLeadingZero() ? "0" : "");
1641 nationalNumber.append(number.getNationalNumber());
1642 return nationalNumber.toString();
1646 * A helper function that is used by format and formatByPattern.
1648 private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1649 PhoneNumberFormat numberFormat,
1650 StringBuilder formattedNumber) {
1651 switch (numberFormat) {
1653 formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1656 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1659 formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1660 .insert(0, RFC3966_PREFIX);
1668 // Simple wrapper of formatNsn for the common case of no carrier code.
1669 private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1670 return formatNsn(number, metadata, numberFormat, null);
1673 // Note in some regions, the national number can be written in two completely different ways
1674 // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1675 // numberFormat parameter here is used to specify which format to use for those cases. If a
1676 // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1677 private String formatNsn(String number,
1678 PhoneMetadata metadata,
1679 PhoneNumberFormat numberFormat,
1680 String carrierCode) {
1681 List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
1682 // When the intlNumberFormats exists, we use that to format national number for the
1683 // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1684 List<NumberFormat> availableFormats =
1685 (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
1686 ? metadata.numberFormats()
1687 : metadata.intlNumberFormats();
1688 NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1689 return (formattingPattern == null)
1691 : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
1694 NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1695 String nationalNumber) {
1696 for (NumberFormat numFormat : availableFormats) {
1697 int size = numFormat.leadingDigitsPatternSize();
1698 if (size == 0 || regexCache.getPatternForRegex(
1699 // We always use the last leading_digits_pattern, as it is the most detailed.
1700 numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
1701 Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1710 // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1711 String formatNsnUsingPattern(String nationalNumber,
1712 NumberFormat formattingPattern,
1713 PhoneNumberFormat numberFormat) {
1714 return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
1717 // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1719 private String formatNsnUsingPattern(String nationalNumber,
1720 NumberFormat formattingPattern,
1721 PhoneNumberFormat numberFormat,
1722 String carrierCode) {
1723 String numberFormatRule = formattingPattern.getFormat();
1725 regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1726 String formattedNationalNumber = "";
1727 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1728 carrierCode != null && carrierCode.length() > 0 &&
1729 formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1730 // Replace the $CC in the formatting rule with the desired carrier code.
1731 String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1732 carrierCodeFormattingRule =
1733 CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
1734 // Now replace the $FG in the formatting rule with the first group and the carrier code
1735 // combined in the appropriate way.
1736 numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
1737 .replaceFirst(carrierCodeFormattingRule);
1738 formattedNationalNumber = m.replaceAll(numberFormatRule);
1740 // Use the national prefix formatting rule instead.
1741 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1742 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1743 nationalPrefixFormattingRule != null &&
1744 nationalPrefixFormattingRule.length() > 0) {
1745 Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
1746 formattedNationalNumber =
1747 m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
1749 formattedNationalNumber = m.replaceAll(numberFormatRule);
1752 if (numberFormat == PhoneNumberFormat.RFC3966) {
1753 // Strip any leading punctuation.
1754 Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
1755 if (matcher.lookingAt()) {
1756 formattedNationalNumber = matcher.replaceFirst("");
1758 // Replace the rest with a dash between each number group.
1759 formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
1761 return formattedNationalNumber;
1765 * Gets a valid number for the specified region.
1767 * @param regionCode the region for which an example number is needed
1768 * @return a valid fixed-line number for the specified region. Returns null when the metadata
1769 * does not contain such information, or the region 001 is passed in. For 001 (representing
1770 * non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
1772 public PhoneNumber getExampleNumber(String regionCode) {
1773 return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
1777 * Gets a valid number for the specified region and number type.
1779 * @param regionCode the region for which an example number is needed
1780 * @param type the type of number that is needed
1781 * @return a valid number for the specified region and type. Returns null when the metadata
1782 * does not contain such information or if an invalid region or region 001 was entered.
1783 * For 001 (representing non-geographical numbers), call
1784 * {@link #getExampleNumberForNonGeoEntity} instead.
1786 public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
1787 // Check the region code is valid.
1788 if (!isValidRegionCode(regionCode)) {
1789 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
1792 PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
1794 if (desc.hasExampleNumber()) {
1795 return parse(desc.getExampleNumber(), regionCode);
1797 } catch (NumberParseException e) {
1798 logger.log(Level.SEVERE, e.toString());
1804 * Gets a valid number for the specified country calling code for a non-geographical entity.
1806 * @param countryCallingCode the country calling code for a non-geographical entity
1807 * @return a valid number for the non-geographical entity. Returns null when the metadata
1808 * does not contain such information, or the country calling code passed in does not belong
1809 * to a non-geographical entity.
1811 public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
1812 PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
1813 if (metadata != null) {
1814 PhoneNumberDesc desc = metadata.getGeneralDesc();
1816 if (desc.hasExampleNumber()) {
1817 return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
1819 } catch (NumberParseException e) {
1820 logger.log(Level.SEVERE, e.toString());
1823 logger.log(Level.WARNING,
1824 "Invalid or unknown country calling code provided: " + countryCallingCode);
1830 * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1831 * an extension specified.
1833 private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
1834 PhoneNumberFormat numberFormat,
1835 StringBuilder formattedNumber) {
1836 if (number.hasExtension() && number.getExtension().length() > 0) {
1837 if (numberFormat == PhoneNumberFormat.RFC3966) {
1838 formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
1840 if (metadata.hasPreferredExtnPrefix()) {
1841 formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
1843 formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
1849 PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
1852 return metadata.getPremiumRate();
1854 return metadata.getTollFree();
1856 return metadata.getMobile();
1858 case FIXED_LINE_OR_MOBILE:
1859 return metadata.getFixedLine();
1861 return metadata.getSharedCost();
1863 return metadata.getVoip();
1864 case PERSONAL_NUMBER:
1865 return metadata.getPersonalNumber();
1867 return metadata.getPager();
1869 return metadata.getUan();
1871 return metadata.getVoicemail();
1873 return metadata.getGeneralDesc();
1878 * Gets the type of a phone number.
1880 * @param number the phone number that we want to know the type
1881 * @return the type of the phone number
1883 public PhoneNumberType getNumberType(PhoneNumber number) {
1884 String regionCode = getRegionCodeForNumber(number);
1885 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
1886 if (metadata == null) {
1887 return PhoneNumberType.UNKNOWN;
1889 String nationalSignificantNumber = getNationalSignificantNumber(number);
1890 return getNumberTypeHelper(nationalSignificantNumber, metadata);
1893 private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
1894 PhoneNumberDesc generalNumberDesc = metadata.getGeneralDesc();
1895 if (!generalNumberDesc.hasNationalNumberPattern() ||
1896 !isNumberMatchingDesc(nationalNumber, generalNumberDesc)) {
1897 return PhoneNumberType.UNKNOWN;
1900 if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
1901 return PhoneNumberType.PREMIUM_RATE;
1903 if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
1904 return PhoneNumberType.TOLL_FREE;
1906 if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
1907 return PhoneNumberType.SHARED_COST;
1909 if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
1910 return PhoneNumberType.VOIP;
1912 if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
1913 return PhoneNumberType.PERSONAL_NUMBER;
1915 if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
1916 return PhoneNumberType.PAGER;
1918 if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
1919 return PhoneNumberType.UAN;
1921 if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
1922 return PhoneNumberType.VOICEMAIL;
1925 boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
1927 if (metadata.isSameMobileAndFixedLinePattern()) {
1928 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
1929 } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
1930 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
1932 return PhoneNumberType.FIXED_LINE;
1934 // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
1935 // mobile and fixed line aren't the same.
1936 if (!metadata.isSameMobileAndFixedLinePattern() &&
1937 isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
1938 return PhoneNumberType.MOBILE;
1940 return PhoneNumberType.UNKNOWN;
1944 * Returns the metadata for the given region code or {@code null} if the region code is invalid
1947 PhoneMetadata getMetadataForRegion(String regionCode) {
1948 if (!isValidRegionCode(regionCode)) {
1951 synchronized (regionToMetadataMap) {
1952 if (!regionToMetadataMap.containsKey(regionCode)) {
1953 // The regionCode here will be valid and won't be '001', so we don't need to worry about
1954 // what to pass in for the country calling code.
1955 loadMetadataFromFile(currentFilePrefix, regionCode, 0);
1958 return regionToMetadataMap.get(regionCode);
1961 PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
1962 synchronized (countryCodeToNonGeographicalMetadataMap) {
1963 if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
1966 if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
1967 loadMetadataFromFile(currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode);
1970 return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
1973 // @VisibleForTesting
1974 boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
1975 Matcher possibleNumberPatternMatcher =
1976 regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
1977 .matcher(nationalNumber);
1978 return possibleNumberPatternMatcher.matches();
1981 // @VisibleForTesting
1982 boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
1983 Matcher nationalNumberPatternMatcher =
1984 regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
1985 .matcher(nationalNumber);
1986 return isNumberPossibleForDesc(nationalNumber, numberDesc) &&
1987 nationalNumberPatternMatcher.matches();
1991 * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
1992 * is actually in use, which is impossible to tell by just looking at a number itself.
1994 * @param number the phone number that we want to validate
1995 * @return a boolean that indicates whether the number is of a valid pattern
1997 public boolean isValidNumber(PhoneNumber number) {
1998 String regionCode = getRegionCodeForNumber(number);
1999 return isValidNumberForRegion(number, regionCode);
2003 * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2004 * is actually in use, which is impossible to tell by just looking at a number itself. If the
2005 * country calling code is not the same as the country calling code for the region, this
2006 * immediately exits with false. After this, the specific number pattern rules for the region are
2007 * examined. This is useful for determining for example whether a particular number is valid for
2008 * Canada, rather than just a valid NANPA number.
2009 * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2010 * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2011 * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2014 * @param number the phone number that we want to validate
2015 * @param regionCode the region that we want to validate the phone number for
2016 * @return a boolean that indicates whether the number is of a valid pattern
2018 public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2019 int countryCode = number.getCountryCode();
2020 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2021 if ((metadata == null) ||
2022 (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
2023 countryCode != getCountryCodeForValidRegion(regionCode))) {
2024 // Either the region code was invalid, or the country calling code for this number does not
2025 // match that of the region code.
2028 PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
2029 String nationalSignificantNumber = getNationalSignificantNumber(number);
2031 // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in
2032 // as a valid number if its national significant number is between the minimum and maximum
2033 // lengths defined by ITU for a national significant number.
2034 if (!generalNumDesc.hasNationalNumberPattern()) {
2035 int numberLength = nationalSignificantNumber.length();
2036 return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN;
2038 return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
2042 * Returns the region where a phone number is from. This could be used for geocoding at the region
2045 * @param number the phone number whose origin we want to know
2046 * @return the region where the phone number is from, or null if no region matches this calling
2049 public String getRegionCodeForNumber(PhoneNumber number) {
2050 int countryCode = number.getCountryCode();
2051 List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
2052 if (regions == null) {
2053 String numberString = getNationalSignificantNumber(number);
2054 logger.log(Level.WARNING,
2055 "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
2058 if (regions.size() == 1) {
2059 return regions.get(0);
2061 return getRegionCodeForNumberFromRegionList(number, regions);
2065 private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
2066 List<String> regionCodes) {
2067 String nationalNumber = getNationalSignificantNumber(number);
2068 for (String regionCode : regionCodes) {
2069 // If leadingDigits is present, use this. Otherwise, do full validation.
2070 // Metadata cannot be null because the region codes come from the country calling code map.
2071 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2072 if (metadata.hasLeadingDigits()) {
2073 if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
2074 .matcher(nationalNumber).lookingAt()) {
2077 } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
2085 * Returns the region code that matches the specific country calling code. In the case of no
2086 * region code being found, ZZ will be returned. In the case of multiple regions, the one
2087 * designated in the metadata as the "main" region for this calling code will be returned.
2089 public String getRegionCodeForCountryCode(int countryCallingCode) {
2090 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2091 return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
2095 * Returns a list with the region codes that match the specific country calling code. For
2096 * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2097 * of no region code being found, an empty list is returned.
2099 public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2100 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2101 return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2106 * Returns the country calling code for a specific region. For example, this would be 1 for the
2107 * United States, and 64 for New Zealand.
2109 * @param regionCode the region that we want to get the country calling code for
2110 * @return the country calling code for the region denoted by regionCode
2112 public int getCountryCodeForRegion(String regionCode) {
2113 if (!isValidRegionCode(regionCode)) {
2114 logger.log(Level.WARNING,
2115 "Invalid or missing region code ("
2116 + ((regionCode == null) ? "null" : regionCode)
2120 return getCountryCodeForValidRegion(regionCode);
2124 * Returns the country calling code for a specific region. For example, this would be 1 for the
2125 * United States, and 64 for New Zealand. Assumes the region is already valid.
2127 * @param regionCode the region that we want to get the country calling code for
2128 * @return the country calling code for the region denoted by regionCode
2129 * @throws IllegalArgumentException if the region is invalid
2131 private int getCountryCodeForValidRegion(String regionCode) {
2132 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2133 if (metadata == null) {
2134 throw new IllegalArgumentException("Invalid region code: " + regionCode);
2136 return metadata.getCountryCode();
2140 * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2141 * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2142 * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2143 * present, we return null.
2145 * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2146 * national dialling prefix is used only for certain types of numbers. Use the library's
2147 * formatting functions to prefix the national prefix when required.
2149 * @param regionCode the region that we want to get the dialling prefix for
2150 * @param stripNonDigits true to strip non-digits from the national dialling prefix
2151 * @return the dialling prefix for the region denoted by regionCode
2153 public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2154 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2155 if (metadata == null) {
2156 logger.log(Level.WARNING,
2157 "Invalid or missing region code ("
2158 + ((regionCode == null) ? "null" : regionCode)
2162 String nationalPrefix = metadata.getNationalPrefix();
2163 // If no national prefix was found, we return null.
2164 if (nationalPrefix.length() == 0) {
2167 if (stripNonDigits) {
2168 // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2169 // to be removed here as well.
2170 nationalPrefix = nationalPrefix.replace("~", "");
2172 return nationalPrefix;
2176 * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2178 * @return true if regionCode is one of the regions under NANPA
2180 public boolean isNANPACountry(String regionCode) {
2181 return nanpaRegions.contains(regionCode);
2185 * Checks whether the country calling code is from a region whose national significant number
2186 * could contain a leading zero. An example of such a region is Italy. Returns false if no
2187 * metadata for the country is found.
2189 boolean isLeadingZeroPossible(int countryCallingCode) {
2190 PhoneMetadata mainMetadataForCallingCode =
2191 getMetadataForRegionOrCallingCode(countryCallingCode,
2192 getRegionCodeForCountryCode(countryCallingCode));
2193 if (mainMetadataForCallingCode == null) {
2196 return mainMetadataForCallingCode.isLeadingZeroPossible();
2200 * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2201 * number will start with at least 3 digits and will have three or more alpha characters. This
2202 * does not do region-specific checks - to work out if this number is actually valid for a region,
2203 * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2204 * {@link #isValidNumber} should be used.
2206 * @param number the number that needs to be checked
2207 * @return true if the number is a valid vanity number
2209 public boolean isAlphaNumber(String number) {
2210 if (!isViablePhoneNumber(number)) {
2211 // Number is too short, or doesn't match the basic phone number pattern.
2214 StringBuilder strippedNumber = new StringBuilder(number);
2215 maybeStripExtension(strippedNumber);
2216 return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2220 * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2221 * for failure, this method returns a boolean value.
2222 * @param number the number that needs to be checked
2223 * @return true if the number is possible
2225 public boolean isPossibleNumber(PhoneNumber number) {
2226 return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
2230 * Helper method to check a number against a particular pattern and determine whether it matches,
2231 * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
2232 * and 10 are possible, and a number in between these possible lengths is entered, such as of
2233 * length 8, this will return TOO_LONG.
2235 private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
2236 Matcher numberMatcher = numberPattern.matcher(number);
2237 if (numberMatcher.matches()) {
2238 return ValidationResult.IS_POSSIBLE;
2240 if (numberMatcher.lookingAt()) {
2241 return ValidationResult.TOO_LONG;
2243 return ValidationResult.TOO_SHORT;
2248 * Check whether a phone number is a possible number. It provides a more lenient check than
2249 * {@link #isValidNumber} in the following sense:
2251 * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
2252 * digits of the number.
2253 * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2254 * applies to all types of phone numbers in a region. Therefore, it is much faster than
2256 * <li> For fixed line numbers, many regions have the concept of area code, which together with
2257 * subscriber number constitute the national significant number. It is sometimes okay to dial
2258 * the subscriber number only when dialing in the same area. This function will return
2259 * true if the subscriber-number-only version is passed in. On the other hand, because
2260 * isValidNumber validates using information on both starting digits (for fixed line
2261 * numbers, that would most likely be area codes) and length (obviously includes the
2262 * length of area codes for fixed line numbers), it will return false for the
2263 * subscriber-number-only version.
2265 * @param number the number that needs to be checked
2266 * @return a ValidationResult object which indicates whether the number is possible
2268 public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2269 String nationalNumber = getNationalSignificantNumber(number);
2270 int countryCode = number.getCountryCode();
2271 // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
2272 // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
2273 // valid. This would need to be revisited if the possible number pattern ever differed between
2274 // various regions within those plans.
2275 if (!hasValidCountryCallingCode(countryCode)) {
2276 return ValidationResult.INVALID_COUNTRY_CODE;
2278 String regionCode = getRegionCodeForCountryCode(countryCode);
2279 // Metadata cannot be null because the country calling code is valid.
2280 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2281 PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
2282 // Handling case of numbers with no metadata.
2283 if (!generalNumDesc.hasNationalNumberPattern()) {
2284 logger.log(Level.FINER, "Checking if number is possible with incomplete metadata.");
2285 int numberLength = nationalNumber.length();
2286 if (numberLength < MIN_LENGTH_FOR_NSN) {
2287 return ValidationResult.TOO_SHORT;
2288 } else if (numberLength > MAX_LENGTH_FOR_NSN) {
2289 return ValidationResult.TOO_LONG;
2291 return ValidationResult.IS_POSSIBLE;
2294 Pattern possibleNumberPattern =
2295 regexCache.getPatternForRegex(generalNumDesc.getPossibleNumberPattern());
2296 return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
2300 * Check whether a phone number is a possible number given a number in the form of a string, and
2301 * the region where the number could be dialed from. It provides a more lenient check than
2302 * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
2304 * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
2305 * with the resultant PhoneNumber object.
2307 * @param number the number that needs to be checked, in the form of a string
2308 * @param regionDialingFrom the region that we are expecting the number to be dialed from.
2309 * Note this is different from the region where the number belongs. For example, the number
2310 * +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2311 * dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2312 * region which uses an international dialling prefix of 00. When it is written as
2313 * 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2314 * can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
2316 * @return true if the number is possible
2318 public boolean isPossibleNumber(String number, String regionDialingFrom) {
2320 return isPossibleNumber(parse(number, regionDialingFrom));
2321 } catch (NumberParseException e) {
2327 * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2328 * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2329 * the PhoneNumber object passed in will not be modified.
2330 * @param number a PhoneNumber object which contains a number that is too long to be valid.
2331 * @return true if a valid phone number can be successfully extracted.
2333 public boolean truncateTooLongNumber(PhoneNumber number) {
2334 if (isValidNumber(number)) {
2337 PhoneNumber numberCopy = new PhoneNumber();
2338 numberCopy.mergeFrom(number);
2339 long nationalNumber = number.getNationalNumber();
2341 nationalNumber /= 10;
2342 numberCopy.setNationalNumber(nationalNumber);
2343 if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
2344 nationalNumber == 0) {
2347 } while (!isValidNumber(numberCopy));
2348 number.setNationalNumber(nationalNumber);
2353 * Gets an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
2355 * @param regionCode the region where the phone number is being entered
2356 * @return an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2357 * to format phone numbers in the specific region "as you type"
2359 public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
2360 return new AsYouTypeFormatter(regionCode);
2363 // Extracts country calling code from fullNumber, returns it and places the remaining number in
2364 // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2365 // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2367 int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2368 if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2369 // Country codes do not begin with a '0'.
2372 int potentialCountryCode;
2373 int numberLength = fullNumber.length();
2374 for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
2375 potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2376 if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
2377 nationalNumber.append(fullNumber.substring(i));
2378 return potentialCountryCode;
2385 * Tries to extract a country calling code from a number. This method will return zero if no
2386 * country calling code is considered to be present. Country calling codes are extracted in the
2389 * <li> by stripping the international dialing prefix of the region the person is dialing from,
2390 * if this is present in the number, and looking at the next digits
2391 * <li> by stripping the '+' sign if present and then looking at the next digits
2392 * <li> by comparing the start of the number and the country calling code of the default region.
2393 * If the number is not considered possible for the numbering plan of the default region
2394 * initially, but starts with the country calling code of this region, validation will be
2395 * reattempted after stripping this country calling code. If this number is considered a
2396 * possible number, then the first digits will be considered the country calling code and
2399 * It will throw a NumberParseException if the number starts with a '+' but the country calling
2400 * code supplied after this does not match that of any known region.
2402 * @param number non-normalized telephone number that we wish to extract a country calling
2403 * code from - may begin with '+'
2404 * @param defaultRegionMetadata metadata about the region this number may be from
2405 * @param nationalNumber a string buffer to store the national significant number in, in the case
2406 * that a country calling code was extracted. The number is appended to any existing contents.
2407 * If no country calling code was extracted, this will be left unchanged.
2408 * @param keepRawInput true if the country_code_source and preferred_carrier_code fields of
2409 * phoneNumber should be populated.
2410 * @param phoneNumber the PhoneNumber object where the country_code and country_code_source need
2411 * to be populated. Note the country_code is always populated, whereas country_code_source is
2412 * only populated when keepCountryCodeSource is true.
2413 * @return the country calling code extracted or 0 if none could be extracted
2415 // @VisibleForTesting
2416 int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
2417 StringBuilder nationalNumber, boolean keepRawInput,
2418 PhoneNumber phoneNumber)
2419 throws NumberParseException {
2420 if (number.length() == 0) {
2423 StringBuilder fullNumber = new StringBuilder(number);
2424 // Set the default prefix to be something that will never match.
2425 String possibleCountryIddPrefix = "NonMatch";
2426 if (defaultRegionMetadata != null) {
2427 possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
2430 CountryCodeSource countryCodeSource =
2431 maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
2433 phoneNumber.setCountryCodeSource(countryCodeSource);
2435 if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2436 if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
2437 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2438 "Phone number had an IDD, but after this was not "
2439 + "long enough to be a viable phone number.");
2441 int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
2442 if (potentialCountryCode != 0) {
2443 phoneNumber.setCountryCode(potentialCountryCode);
2444 return potentialCountryCode;
2447 // If this fails, they must be using a strange country calling code that we don't recognize,
2448 // or that doesn't exist.
2449 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2450 "Country calling code supplied was not recognised.");
2451 } else if (defaultRegionMetadata != null) {
2452 // Check to see if the number starts with the country calling code for the default region. If
2453 // so, we remove the country calling code, and do some checks on the validity of the number
2454 // before and after.
2455 int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2456 String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2457 String normalizedNumber = fullNumber.toString();
2458 if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2459 StringBuilder potentialNationalNumber =
2460 new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
2461 PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2462 Pattern validNumberPattern =
2463 regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
2464 maybeStripNationalPrefixAndCarrierCode(
2465 potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2466 Pattern possibleNumberPattern =
2467 regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
2468 // If the number was not valid before but is valid now, or if it was too long before, we
2469 // consider the number with the country calling code stripped to be a better result and
2470 // keep that instead.
2471 if ((!validNumberPattern.matcher(fullNumber).matches() &&
2472 validNumberPattern.matcher(potentialNationalNumber).matches()) ||
2473 testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
2474 == ValidationResult.TOO_LONG) {
2475 nationalNumber.append(potentialNationalNumber);
2477 phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
2479 phoneNumber.setCountryCode(defaultCountryCode);
2480 return defaultCountryCode;
2484 // No country calling code present.
2485 phoneNumber.setCountryCode(0);
2490 * Strips the IDD from the start of the number if present. Helper function used by
2491 * maybeStripInternationalPrefixAndNormalize.
2493 private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
2494 Matcher m = iddPattern.matcher(number);
2495 if (m.lookingAt()) {
2496 int matchEnd = m.end();
2497 // Only strip this if the first digit after the match is not a 0, since country calling codes
2498 // cannot begin with 0.
2499 Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
2500 if (digitMatcher.find()) {
2501 String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
2502 if (normalizedGroup.equals("0")) {
2506 number.delete(0, matchEnd);
2513 * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2514 * the resulting number, and indicates if an international prefix was present.
2516 * @param number the non-normalized telephone number that we wish to strip any international
2517 * dialing prefix from.
2518 * @param possibleIddPrefix the international direct dialing prefix from the region we
2519 * think this number may be dialed in
2520 * @return the corresponding CountryCodeSource if an international dialing prefix could be
2521 * removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2522 * not seem to be in international format.
2524 // @VisibleForTesting
2525 CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2526 StringBuilder number,
2527 String possibleIddPrefix) {
2528 if (number.length() == 0) {
2529 return CountryCodeSource.FROM_DEFAULT_COUNTRY;
2531 // Check to see if the number begins with one or more plus signs.
2532 Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2533 if (m.lookingAt()) {
2534 number.delete(0, m.end());
2535 // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
2537 return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
2539 // Attempt to parse the first digits as an international prefix.
2540 Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
2542 return parsePrefixAsIdd(iddPattern, number)
2543 ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2544 : CountryCodeSource.FROM_DEFAULT_COUNTRY;
2548 * Strips any national prefix (such as 0, 1) present in the number provided.
2550 * @param number the normalized telephone number that we wish to strip any national
2551 * dialing prefix from
2552 * @param metadata the metadata for the region that we think this number is from
2553 * @param carrierCode a place to insert the carrier code if one is extracted
2554 * @return true if a national prefix or carrier code (or both) could be extracted.
2556 // @VisibleForTesting
2557 boolean maybeStripNationalPrefixAndCarrierCode(
2558 StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
2559 int numberLength = number.length();
2560 String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
2561 if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
2562 // Early return for numbers of zero length.
2565 // Attempt to parse the first digits as a national prefix.
2566 Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
2567 if (prefixMatcher.lookingAt()) {
2568 Pattern nationalNumberRule =
2569 regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
2570 // Check if the original number is viable.
2571 boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
2572 // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
2573 // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
2574 // remove the national prefix.
2575 int numOfGroups = prefixMatcher.groupCount();
2576 String transformRule = metadata.getNationalPrefixTransformRule();
2577 if (transformRule == null || transformRule.length() == 0 ||
2578 prefixMatcher.group(numOfGroups) == null) {
2579 // If the original number was viable, and the resultant number is not, we return.
2580 if (isViableOriginalNumber &&
2581 !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
2584 if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
2585 carrierCode.append(prefixMatcher.group(1));
2587 number.delete(0, prefixMatcher.end());
2590 // Check that the resultant number is still viable. If not, return. Check this by copying
2591 // the string buffer and making the transformation on the copy first.
2592 StringBuilder transformedNumber = new StringBuilder(number);
2593 transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
2594 if (isViableOriginalNumber &&
2595 !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
2598 if (carrierCode != null && numOfGroups > 1) {
2599 carrierCode.append(prefixMatcher.group(1));
2601 number.replace(0, number.length(), transformedNumber.toString());
2609 * Strips any extension (as in, the part of the number dialled after the call is connected,
2610 * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
2612 * @param number the non-normalized telephone number that we wish to strip the extension from
2613 * @return the phone extension
2615 // @VisibleForTesting
2616 String maybeStripExtension(StringBuilder number) {
2617 Matcher m = EXTN_PATTERN.matcher(number);
2618 // If we find a potential extension, and the number preceding this is a viable number, we assume
2619 // it is an extension.
2620 if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
2621 // The numbers are captured into groups in the regular expression.
2622 for (int i = 1, length = m.groupCount(); i <= length; i++) {
2623 if (m.group(i) != null) {
2624 // We go through the capturing groups until we find one that captured some digits. If none
2625 // did, then we will return the empty string.
2626 String extension = m.group(i);
2627 number.delete(m.start(), number.length());
2636 * Checks to see that the region code used is valid, or if it is not valid, that the number to
2637 * parse starts with a + symbol so that we can attempt to infer the region from the number.
2638 * Returns false if it cannot use the region provided and the region cannot be inferred.
2640 private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
2641 if (!isValidRegionCode(defaultRegion)) {
2642 // If the number is null or empty, we can't infer the region.
2643 if (numberToParse == null || numberToParse.length() == 0 ||
2644 !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
2652 * Parses a string and returns it in proto buffer format. This method will throw a
2653 * {@link com.google.i18n.phonenumbers.NumberParseException} if the number is not considered to be
2654 * a possible number. Note that validation of whether the number is actually a valid number for a
2655 * particular region is not performed. This can be done separately with {@link #isValidNumber}.
2657 * @param numberToParse number that we are attempting to parse. This can contain formatting
2658 * such as +, ( and -, as well as a phone number extension. It can also
2659 * be provided in RFC3966 format.
2660 * @param defaultRegion region that we are expecting the number to be from. This is only used
2661 * if the number being parsed is not written in international format.
2662 * The country_code for the number in this case would be stored as that
2663 * of the default region supplied. If the number is guaranteed to
2664 * start with a '+' followed by the country calling code, then
2665 * "ZZ" or null can be supplied.
2666 * @return a phone number proto buffer filled with the parsed number
2667 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2668 * no default region was supplied and the number is not in
2669 * international format (does not start with +)
2671 public PhoneNumber parse(String numberToParse, String defaultRegion)
2672 throws NumberParseException {
2673 PhoneNumber phoneNumber = new PhoneNumber();
2674 parse(numberToParse, defaultRegion, phoneNumber);
2679 * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
2680 * decrease object creation when invoked many times.
2682 public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
2683 throws NumberParseException {
2684 parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
2688 * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
2689 * in that it always populates the raw_input field of the protocol buffer with numberToParse as
2690 * well as the country_code_source field.
2692 * @param numberToParse number that we are attempting to parse. This can contain formatting
2693 * such as +, ( and -, as well as a phone number extension.
2694 * @param defaultRegion region that we are expecting the number to be from. This is only used
2695 * if the number being parsed is not written in international format.
2696 * The country calling code for the number in this case would be stored
2697 * as that of the default region supplied.
2698 * @return a phone number proto buffer filled with the parsed number
2699 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2700 * no default region was supplied
2702 public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
2703 throws NumberParseException {
2704 PhoneNumber phoneNumber = new PhoneNumber();
2705 parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
2710 * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
2711 * a parameter to decrease object creation when invoked many times.
2713 public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
2714 PhoneNumber phoneNumber)
2715 throws NumberParseException {
2716 parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
2720 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
2721 * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
2722 * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
2724 * @param text the text to search for phone numbers, null for no text
2725 * @param defaultRegion region that we are expecting the number to be from. This is only used
2726 * if the number being parsed is not written in international format. The
2727 * country_code for the number in this case would be stored as that of
2728 * the default region supplied. May be null if only international
2729 * numbers are expected.
2731 public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
2732 return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
2736 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
2738 * @param text the text to search for phone numbers, null for no text
2739 * @param defaultRegion region that we are expecting the number to be from. This is only used
2740 * if the number being parsed is not written in international format. The
2741 * country_code for the number in this case would be stored as that of
2742 * the default region supplied. May be null if only international
2743 * numbers are expected.
2744 * @param leniency the leniency to use when evaluating candidate phone numbers
2745 * @param maxTries the maximum number of invalid numbers to try before giving up on the
2746 * text. This is to cover degenerate cases where the text has a lot of
2747 * false positives in it. Must be {@code >= 0}.
2749 public Iterable<PhoneNumberMatch> findNumbers(
2750 final CharSequence text, final String defaultRegion, final Leniency leniency,
2751 final long maxTries) {
2753 return new Iterable<PhoneNumberMatch>() {
2754 public Iterator<PhoneNumberMatch> iterator() {
2755 return new PhoneNumberMatcher(
2756 PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
2762 * Parses a string and fills up the phoneNumber. This method is the same as the public
2763 * parse() method, with the exception that it allows the default region to be null, for use by
2764 * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
2765 * to be null or unknown ("ZZ").
2767 private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
2768 boolean checkRegion, PhoneNumber phoneNumber)
2769 throws NumberParseException {
2770 if (numberToParse == null) {
2771 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2772 "The phone number supplied was null.");
2773 } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
2774 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2775 "The string supplied was too long to parse.");
2778 StringBuilder nationalNumber = new StringBuilder();
2779 buildNationalNumberForParsing(numberToParse, nationalNumber);
2781 if (!isViablePhoneNumber(nationalNumber.toString())) {
2782 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2783 "The string supplied did not seem to be a phone number.");
2786 // Check the region supplied is valid, or that the extracted number starts with some sort of +
2787 // sign so the number's region can be determined.
2788 if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
2789 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2790 "Missing or invalid default region.");
2794 phoneNumber.setRawInput(numberToParse);
2796 // Attempt to parse extension first, since it doesn't require region-specific data and we want
2797 // to have the non-normalised number here.
2798 String extension = maybeStripExtension(nationalNumber);
2799 if (extension.length() > 0) {
2800 phoneNumber.setExtension(extension);
2803 PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
2804 // Check to see if the number is given in international format so we know whether this number is
2805 // from the default region or not.
2806 StringBuilder normalizedNationalNumber = new StringBuilder();
2807 int countryCode = 0;
2809 // TODO: This method should really just take in the string buffer that has already
2810 // been created, and just remove the prefix, rather than taking in a string and then
2811 // outputting a string buffer.
2812 countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
2813 normalizedNationalNumber, keepRawInput, phoneNumber);
2814 } catch (NumberParseException e) {
2815 Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
2816 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
2817 matcher.lookingAt()) {
2818 // Strip the plus-char, and try again.
2819 countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
2820 regionMetadata, normalizedNationalNumber,
2821 keepRawInput, phoneNumber);
2822 if (countryCode == 0) {
2823 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2824 "Could not interpret numbers after plus-sign.");
2827 throw new NumberParseException(e.getErrorType(), e.getMessage());
2830 if (countryCode != 0) {
2831 String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
2832 if (!phoneNumberRegion.equals(defaultRegion)) {
2833 // Metadata cannot be null because the country calling code is valid.
2834 regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
2837 // If no extracted country calling code, use the region supplied instead. The national number
2838 // is just the normalized version of the number we were given to parse.
2839 normalize(nationalNumber);
2840 normalizedNationalNumber.append(nationalNumber);
2841 if (defaultRegion != null) {
2842 countryCode = regionMetadata.getCountryCode();
2843 phoneNumber.setCountryCode(countryCode);
2844 } else if (keepRawInput) {
2845 phoneNumber.clearCountryCodeSource();
2848 if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
2849 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2850 "The string supplied is too short to be a phone number.");
2852 if (regionMetadata != null) {
2853 StringBuilder carrierCode = new StringBuilder();
2854 maybeStripNationalPrefixAndCarrierCode(normalizedNationalNumber, regionMetadata, carrierCode);
2856 phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
2859 int lengthOfNationalNumber = normalizedNationalNumber.length();
2860 if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
2861 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2862 "The string supplied is too short to be a phone number.");
2864 if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
2865 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2866 "The string supplied is too long to be a phone number.");
2868 if (normalizedNationalNumber.charAt(0) == '0') {
2869 phoneNumber.setItalianLeadingZero(true);
2871 phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
2875 * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
2876 * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
2878 private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
2879 int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
2880 if (indexOfPhoneContext > 0) {
2881 int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
2882 // If the phone context contains a phone number prefix, we need to capture it, whereas domains
2884 if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
2885 // Additional parameters might follow the phone context. If so, we will remove them here
2886 // because the parameters after phone context are not important for parsing the
2888 int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
2889 if (phoneContextEnd > 0) {
2890 nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
2892 nationalNumber.append(numberToParse.substring(phoneContextStart));
2896 // Now append everything between the "tel:" prefix and the phone-context. This should include
2897 // the national number, an optional extension or isdn-subaddress component.
2898 nationalNumber.append(numberToParse.substring(
2899 numberToParse.indexOf(RFC3966_PREFIX) + RFC3966_PREFIX.length(), indexOfPhoneContext));
2901 // Extract a possible number from the string passed in (this strips leading characters that
2902 // could not be the start of a phone number.)
2903 nationalNumber.append(extractPossibleNumber(numberToParse));
2906 // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
2907 // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
2908 int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
2909 if (indexOfIsdn > 0) {
2910 nationalNumber.delete(indexOfIsdn, nationalNumber.length());
2912 // If both phone context and isdn-subaddress are absent but other parameters are present, the
2913 // parameters are left in nationalNumber. This is because we are concerned about deleting
2914 // content from a potential number string when there is no strong evidence that the number is
2915 // actually written in RFC3966.
2919 * Takes two phone numbers and compares them for equality.
2921 * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
2922 * and any extension present are the same.
2923 * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
2925 * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
2926 * the same, and one NSN could be a shorter version of the other number. This includes the case
2927 * where one has an extension specified, and the other does not.
2928 * Returns NO_MATCH otherwise.
2929 * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
2930 * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
2932 * @param firstNumberIn first number to compare
2933 * @param secondNumberIn second number to compare
2935 * @return NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
2936 * of the two numbers, described in the method definition.
2938 public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
2939 // Make copies of the phone number so that the numbers passed in are not edited.
2940 PhoneNumber firstNumber = new PhoneNumber();
2941 firstNumber.mergeFrom(firstNumberIn);
2942 PhoneNumber secondNumber = new PhoneNumber();
2943 secondNumber.mergeFrom(secondNumberIn);
2944 // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
2945 // empty-string extensions so that we can use the proto-buffer equality method.
2946 firstNumber.clearRawInput();
2947 firstNumber.clearCountryCodeSource();
2948 firstNumber.clearPreferredDomesticCarrierCode();
2949 secondNumber.clearRawInput();
2950 secondNumber.clearCountryCodeSource();
2951 secondNumber.clearPreferredDomesticCarrierCode();
2952 if (firstNumber.hasExtension() &&
2953 firstNumber.getExtension().length() == 0) {
2954 firstNumber.clearExtension();
2956 if (secondNumber.hasExtension() &&
2957 secondNumber.getExtension().length() == 0) {
2958 secondNumber.clearExtension();
2960 // Early exit if both had extensions and these are different.
2961 if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
2962 !firstNumber.getExtension().equals(secondNumber.getExtension())) {
2963 return MatchType.NO_MATCH;
2965 int firstNumberCountryCode = firstNumber.getCountryCode();
2966 int secondNumberCountryCode = secondNumber.getCountryCode();
2967 // Both had country_code specified.
2968 if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
2969 if (firstNumber.exactlySameAs(secondNumber)) {
2970 return MatchType.EXACT_MATCH;
2971 } else if (firstNumberCountryCode == secondNumberCountryCode &&
2972 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
2973 // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
2974 // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
2975 // shorter variant of the other.
2976 return MatchType.SHORT_NSN_MATCH;
2978 // This is not a match.
2979 return MatchType.NO_MATCH;
2981 // Checks cases where one or both country_code fields were not specified. To make equality
2982 // checks easier, we first set the country_code fields to be equal.
2983 firstNumber.setCountryCode(secondNumberCountryCode);
2984 // If all else was the same, then this is an NSN_MATCH.
2985 if (firstNumber.exactlySameAs(secondNumber)) {
2986 return MatchType.NSN_MATCH;
2988 if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
2989 return MatchType.SHORT_NSN_MATCH;
2991 return MatchType.NO_MATCH;
2994 // Returns true when one national number is the suffix of the other or both are the same.
2995 private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
2996 PhoneNumber secondNumber) {
2997 String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
2998 String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
2999 // Note that endsWith returns true if the numbers are equal.
3000 return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
3001 secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
3005 * Takes two phone numbers as strings and compares them for equality. This is a convenience
3006 * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3008 * @param firstNumber first number to compare. Can contain formatting, and can have country
3009 * calling code specified with + at the start.
3010 * @param secondNumber second number to compare. Can contain formatting, and can have country
3011 * calling code specified with + at the start.
3012 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3013 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3015 public MatchType isNumberMatch(String firstNumber, String secondNumber) {
3017 PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
3018 return isNumberMatch(firstNumberAsProto, secondNumber);
3019 } catch (NumberParseException e) {
3020 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3022 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3023 return isNumberMatch(secondNumberAsProto, firstNumber);
3024 } catch (NumberParseException e2) {
3025 if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3027 PhoneNumber firstNumberProto = new PhoneNumber();
3028 PhoneNumber secondNumberProto = new PhoneNumber();
3029 parseHelper(firstNumber, null, false, false, firstNumberProto);
3030 parseHelper(secondNumber, null, false, false, secondNumberProto);
3031 return isNumberMatch(firstNumberProto, secondNumberProto);
3032 } catch (NumberParseException e3) {
3033 // Fall through and return MatchType.NOT_A_NUMBER.
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;
3044 * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
3045 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3047 * @param firstNumber first number to compare in proto buffer format.
3048 * @param secondNumber second number to compare. Can contain formatting, and can have country
3049 * calling code specified with + at the start.
3050 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3051 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3053 public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
3054 // First see if the second number has an implicit country calling code, by attempting to parse
3057 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3058 return isNumberMatch(firstNumber, secondNumberAsProto);
3059 } catch (NumberParseException e) {
3060 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3061 // The second number has no country calling code. EXACT_MATCH is no longer possible.
3062 // We parse it as if the region was the same as that for the first number, and if
3063 // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3064 String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
3066 if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
3067 PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
3068 MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
3069 if (match == MatchType.EXACT_MATCH) {
3070 return MatchType.NSN_MATCH;
3074 // If the first number didn't have a valid country calling code, then we parse the
3075 // second number without one as well.
3076 PhoneNumber secondNumberProto = new PhoneNumber();
3077 parseHelper(secondNumber, null, false, false, secondNumberProto);
3078 return isNumberMatch(firstNumber, secondNumberProto);
3080 } catch (NumberParseException e2) {
3081 // Fall-through to return NOT_A_NUMBER.
3085 // One or more of the phone numbers we are trying to match is not a viable phone number.
3086 return MatchType.NOT_A_NUMBER;
3090 * Returns true if the number can be dialled from outside the region, or unknown. If the number
3091 * can only be dialled from within the region, returns false. Does not check the number is a valid
3093 * TODO: Make this method public when we have enough metadata to make it worthwhile.
3095 * @param number the phone-number for which we want to know whether it is diallable from
3096 * outside the region
3098 // @VisibleForTesting
3099 boolean canBeInternationallyDialled(PhoneNumber number) {
3100 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3101 if (metadata == null) {
3102 // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3103 // internationally diallable, and will be caught here.
3106 String nationalSignificantNumber = getNationalSignificantNumber(number);
3107 return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());