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.ObjectInput;
29 import java.io.ObjectInputStream;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.List;
39 import java.util.logging.Level;
40 import java.util.logging.Logger;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
45 * Utility for international phone numbers. Functionality includes formatting, parsing and
48 * <p>If you use this library, and want to be notified about important changes, please sign up to
49 * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
51 * NOTE: A lot of methods in this class require Region Code strings. These must be provided using
52 * ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes
54 * http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm
56 * @author Shaopeng Jia
58 public class PhoneNumberUtil {
60 static final MetadataLoader DEFAULT_METADATA_LOADER = new MetadataLoader() {
62 public InputStream loadMetadata(String metadataFileName) {
63 return PhoneNumberUtil.class.getResourceAsStream(metadataFileName);
67 private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName());
69 /** Flags to use when compiling regular expressions for phone numbers. */
70 static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
71 // The minimum and maximum length of the national significant number.
72 private static final int MIN_LENGTH_FOR_NSN = 2;
73 // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
74 static final int MAX_LENGTH_FOR_NSN = 17;
75 // The maximum length of the country calling code.
76 static final int MAX_LENGTH_COUNTRY_CODE = 3;
77 // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
78 // input from overflowing the regular-expression engine.
79 private static final int MAX_INPUT_STRING_LENGTH = 250;
81 private static final String META_DATA_FILE_PREFIX =
82 "/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto";
84 // Region-code for the unknown region.
85 private static final String UNKNOWN_REGION = "ZZ";
87 private static final int NANPA_COUNTRY_CODE = 1;
89 // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
90 // a mobile phone in Colombia.
91 private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
93 // Map of country calling codes that use a mobile token before the area code. One example of when
94 // this is relevant is when determining the length of the national destination code, which should
95 // be the length of the area code plus the length of the mobile token.
96 private static final Map<Integer, String> MOBILE_TOKEN_MAPPINGS;
98 // The PLUS_SIGN signifies the international prefix.
99 static final char PLUS_SIGN = '+';
101 private static final char STAR_SIGN = '*';
103 private static final String RFC3966_EXTN_PREFIX = ";ext=";
104 private static final String RFC3966_PREFIX = "tel:";
105 private static final String RFC3966_PHONE_CONTEXT = ";phone-context=";
106 private static final String RFC3966_ISDN_SUBADDRESS = ";isub=";
108 // A map that contains characters that are essential when dialling. That means any of the
109 // characters in this map must not be removed from a number when dialling, otherwise the call
110 // will not reach the intended destination.
111 private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
113 // Only upper-case variants of alpha characters are stored.
114 private static final Map<Character, Character> ALPHA_MAPPINGS;
116 // For performance reasons, amalgamate both into one map.
117 private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
119 // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
120 // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
121 private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
124 HashMap<Integer, String> mobileTokenMap = new HashMap<Integer, String>();
125 mobileTokenMap.put(52, "1");
126 mobileTokenMap.put(54, "9");
127 MOBILE_TOKEN_MAPPINGS = Collections.unmodifiableMap(mobileTokenMap);
129 // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
130 // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
131 HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
132 asciiDigitMappings.put('0', '0');
133 asciiDigitMappings.put('1', '1');
134 asciiDigitMappings.put('2', '2');
135 asciiDigitMappings.put('3', '3');
136 asciiDigitMappings.put('4', '4');
137 asciiDigitMappings.put('5', '5');
138 asciiDigitMappings.put('6', '6');
139 asciiDigitMappings.put('7', '7');
140 asciiDigitMappings.put('8', '8');
141 asciiDigitMappings.put('9', '9');
143 HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
144 alphaMap.put('A', '2');
145 alphaMap.put('B', '2');
146 alphaMap.put('C', '2');
147 alphaMap.put('D', '3');
148 alphaMap.put('E', '3');
149 alphaMap.put('F', '3');
150 alphaMap.put('G', '4');
151 alphaMap.put('H', '4');
152 alphaMap.put('I', '4');
153 alphaMap.put('J', '5');
154 alphaMap.put('K', '5');
155 alphaMap.put('L', '5');
156 alphaMap.put('M', '6');
157 alphaMap.put('N', '6');
158 alphaMap.put('O', '6');
159 alphaMap.put('P', '7');
160 alphaMap.put('Q', '7');
161 alphaMap.put('R', '7');
162 alphaMap.put('S', '7');
163 alphaMap.put('T', '8');
164 alphaMap.put('U', '8');
165 alphaMap.put('V', '8');
166 alphaMap.put('W', '9');
167 alphaMap.put('X', '9');
168 alphaMap.put('Y', '9');
169 alphaMap.put('Z', '9');
170 ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
172 HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
173 combinedMap.putAll(ALPHA_MAPPINGS);
174 combinedMap.putAll(asciiDigitMappings);
175 ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
177 HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
178 diallableCharMap.putAll(asciiDigitMappings);
179 diallableCharMap.put(PLUS_SIGN, PLUS_SIGN);
180 diallableCharMap.put('*', '*');
181 DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
183 HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
184 // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
185 for (char c : ALPHA_MAPPINGS.keySet()) {
186 allPlusNumberGroupings.put(Character.toLowerCase(c), c);
187 allPlusNumberGroupings.put(c, c);
189 allPlusNumberGroupings.putAll(asciiDigitMappings);
190 // Put grouping symbols.
191 allPlusNumberGroupings.put('-', '-');
192 allPlusNumberGroupings.put('\uFF0D', '-');
193 allPlusNumberGroupings.put('\u2010', '-');
194 allPlusNumberGroupings.put('\u2011', '-');
195 allPlusNumberGroupings.put('\u2012', '-');
196 allPlusNumberGroupings.put('\u2013', '-');
197 allPlusNumberGroupings.put('\u2014', '-');
198 allPlusNumberGroupings.put('\u2015', '-');
199 allPlusNumberGroupings.put('\u2212', '-');
200 allPlusNumberGroupings.put('/', '/');
201 allPlusNumberGroupings.put('\uFF0F', '/');
202 allPlusNumberGroupings.put(' ', ' ');
203 allPlusNumberGroupings.put('\u3000', ' ');
204 allPlusNumberGroupings.put('\u2060', ' ');
205 allPlusNumberGroupings.put('.', '.');
206 allPlusNumberGroupings.put('\uFF0E', '.');
207 ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
210 // Pattern that makes it easy to distinguish whether a region has a unique international dialing
211 // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
212 // represented as a string that contains a sequence of ASCII digits. If there are multiple
213 // available international prefixes in a region, they will be represented as a regex string that
214 // always contains character(s) other than ASCII digits.
215 // Note this regex also includes tilde, which signals waiting for the tone.
216 private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
217 Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
219 // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
220 // found as a leading character only.
221 // This consists of dash characters, white space characters, full stops, slashes,
222 // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
223 // placeholder for carrier information in some phone numbers. Full-width variants are also
225 static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
226 "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
228 private static final String DIGITS = "\\p{Nd}";
229 // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
230 private static final String VALID_ALPHA =
231 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
232 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
233 static final String PLUS_CHARS = "+\uFF0B";
234 static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
235 private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
236 private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
238 // Regular expression of acceptable characters that may start a phone number for the purposes of
239 // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
240 // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
241 // does not contain alpha characters, although they may be used later in the number. It also does
242 // not include other punctuation, as this will be stripped later during parsing and is of no
243 // information value when parsing a number.
244 private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
245 private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
247 // Regular expression of characters typically used to start a second phone number for the purposes
248 // of parsing. This allows us to strip off parts of the number that are actually the start of
249 // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
250 // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
251 // extension so that the first number is parsed correctly.
252 private static final String SECOND_NUMBER_START = "[\\\\/] *x";
253 static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
255 // Regular expression of trailing characters that we want to remove. We remove all characters that
256 // are not alpha or numerical characters. The hash character is retained here, as it may signify
257 // the previous block was an extension.
258 private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
259 static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
261 // We use this pattern to check if the phone number has at least three letters in it - if so, then
262 // we treat it as a number where some phone-number digits are represented by letters.
263 private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
265 // Regular expression of viable phone numbers. This is location independent. Checks we have at
266 // least three leading digits, and only valid punctuation, alpha characters and
267 // digits in the phone number. Does not include extension data.
268 // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
269 // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
271 // Corresponds to the following:
272 // [digits]{minLengthNsn}|
273 // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
275 // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
276 // as "15" etc, but only if there is no punctuation in them. The second expression restricts the
277 // number of digits to three or more, but then allows them to be in international form, and to
278 // have alpha-characters and punctuation.
280 // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
281 private static final String VALID_PHONE_NUMBER =
282 DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" +
283 "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
284 VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
286 // Default extension prefix to use when formatting. This will be put in front of any extension
287 // component of the number, after the main national number is formatted. For example, if you wish
288 // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
289 // as the default extension prefix. This can be overridden by region-specific preferences.
290 private static final String DEFAULT_EXTN_PREFIX = " ext. ";
292 // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
294 private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
295 // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
296 // case-insensitive regexp match. Wide character versions are also provided after each ASCII
298 private static final String EXTN_PATTERNS_FOR_PARSING;
299 static final String EXTN_PATTERNS_FOR_MATCHING;
301 // One-character symbols that can be used to indicate an extension.
302 String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
303 // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
304 // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
306 String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
308 EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
309 EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
313 * Helper initialiser method to create the regular-expression pattern to match extensions,
314 * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
316 private static String createExtnPattern(String singleExtnSymbols) {
317 // There are three regular expressions here. The first covers RFC 3966 format, where the
318 // extension is added using ";ext=". The second more generic one starts with optional white
319 // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
320 // the numbers themselves. The other one covers the special case of American numbers where the
321 // extension is written with a hash at the end, such as "- 503#".
322 // Note that the only capturing groups should be around the digits that you want to capture as
323 // part of the extension, or else parsing will fail!
324 // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
325 // for representing the accented o - the character itself, and one in the unicode decomposed
326 // form with the combining acute accent.
327 return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
328 "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
329 "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
330 "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
331 "[- ]+(" + DIGITS + "{1,5})#");
334 // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
335 // digits, for use when parsing.
336 private static final Pattern EXTN_PATTERN =
337 Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
339 // We append optionally the extension pattern to the end here, as a valid phone number may
340 // have an extension prefix appended, followed by 1 or more digits.
341 private static final Pattern VALID_PHONE_NUMBER_PATTERN =
342 Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
344 static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
346 // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
347 // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
348 // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
350 private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
351 private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
352 private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
353 private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
355 // A pattern that is used to determine if the national prefix formatting rule has the first group
356 // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
357 // for unbalanced parentheses.
358 private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?");
360 private static PhoneNumberUtil instance = null;
362 public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
365 * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
366 * E123. For example, the number of the Google Switzerland office will be written as
367 * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
368 * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
369 * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
370 * separating symbols replaced with a hyphen, and with any phone number extension appended with
371 * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
373 * Note: If you are considering storing the number in a neutral format, you are highly advised to
374 * use the PhoneNumber class.
376 public enum PhoneNumberFormat {
384 * Type of phone numbers.
386 public enum PhoneNumberType {
389 // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
390 // mobile numbers by looking at the phone number itself.
391 FIXED_LINE_OR_MOBILE,
395 // The cost of this call is shared between the caller and the recipient, and is hence typically
396 // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
399 // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
401 // A personal number is associated with a particular person, and may be routed to either a
402 // MOBILE or FIXED_LINE number. Some more information can be found here:
403 // http://en.wikipedia.org/wiki/Personal_Numbers
406 // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
407 // specific offices, but allow one number to be used for a company.
409 // Used for "Voice Mail Access Numbers".
411 // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
417 * Types of phone number matches. See detailed description beside the isNumberMatch() method.
419 public enum MatchType {
428 * Possible outcomes when testing if a PhoneNumber is possible.
430 public enum ValidationResult {
432 INVALID_COUNTRY_CODE,
438 * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
439 * segments. The levels here are ordered in increasing strictness.
441 public enum Leniency {
443 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
444 * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
448 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
449 return util.isPossibleNumber(number);
453 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
454 * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
455 * in national format must have their national-prefix present if it is usually written for a
456 * number of this type.
460 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
461 if (!util.isValidNumber(number) ||
462 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) {
465 return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util);
469 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
470 * are grouped in a possible way for this locale. For example, a US number written as
471 * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
472 * "650 253 0000", "650 2530000" or "6502530000" are.
473 * Numbers with more than one '/' symbol in the national significant number are also dropped at
476 * Warning: This level might result in lower coverage especially for regions outside of country
477 * code "+1". If you are not sure about which level to use, email the discussion group
478 * libphonenumber-discuss@googlegroups.com.
482 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
483 if (!util.isValidNumber(number) ||
484 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
485 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
486 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
489 return PhoneNumberMatcher.checkNumberGroupingIsValid(
490 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
492 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
493 StringBuilder normalizedCandidate,
494 String[] expectedNumberGroups) {
495 return PhoneNumberMatcher.allNumberGroupsRemainGrouped(
496 util, number, normalizedCandidate, expectedNumberGroups);
502 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
503 * are grouped in the same way that we would have formatted it, or as a single block. For
504 * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
505 * "650 253 0000" or "6502530000" are.
506 * Numbers with more than one '/' symbol are also dropped at this level.
508 * Warning: This level might result in lower coverage especially for regions outside of country
509 * code "+1". If you are not sure about which level to use, email the discussion group
510 * libphonenumber-discuss@googlegroups.com.
514 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
515 if (!util.isValidNumber(number) ||
516 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
517 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
518 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
521 return PhoneNumberMatcher.checkNumberGroupingIsValid(
522 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
524 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
525 StringBuilder normalizedCandidate,
526 String[] expectedNumberGroups) {
527 return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent(
528 util, number, normalizedCandidate, expectedNumberGroups);
534 /** Returns true if {@code number} is a verified number according to this leniency. */
535 abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
538 // A mapping from a country calling code to the region codes which denote the region represented
539 // by that country calling code. In the case of multiple regions sharing a calling code, such as
540 // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
542 private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap;
544 // The set of regions that share country calling code 1.
545 // There are roughly 26 regions.
546 // We set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
547 private final Set<String> nanpaRegions = new HashSet<String>(35);
549 // A mapping from a region code to the PhoneMetadata for that region.
550 // Note: Synchronization, though only needed for the Android version of the library, is used in
551 // all versions for consistency.
552 private final Map<String, PhoneMetadata> regionToMetadataMap =
553 Collections.synchronizedMap(new HashMap<String, PhoneMetadata>());
555 // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
556 // that country calling code. Examples of the country calling codes include 800 (International
557 // Toll Free Service) and 808 (International Shared Cost Service).
558 // Note: Synchronization, though only needed for the Android version of the library, is used in
559 // all versions for consistency.
560 private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
561 Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>());
563 // A cache for frequently used region-specific regular expressions.
564 // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on
565 // performance measurements.
566 private final RegexCache regexCache = new RegexCache(100);
568 // The set of regions the library supports.
569 // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
570 // load factor of roughly 0.75.
571 private final Set<String> supportedRegions = new HashSet<String>(320);
573 // The set of county calling codes that map to the non-geo entity region ("001"). This set
574 // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
575 private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>();
577 // The prefix of the metadata files from which region data is loaded.
578 private final String currentFilePrefix;
579 // The metadata loader used to inject alternative metadata sources.
580 private final MetadataLoader metadataLoader;
583 * This class implements a singleton, the constructor is only visible to facilitate testing.
585 // @VisibleForTesting
586 PhoneNumberUtil(String filePrefix, MetadataLoader metadataLoader,
587 Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
588 this.currentFilePrefix = filePrefix;
589 this.metadataLoader = metadataLoader;
590 this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
591 for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) {
592 List<String> regionCodes = entry.getValue();
593 // We can assume that if the county calling code maps to the non-geo entity region code then
594 // that's the only region code it maps to.
595 if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) {
596 // This is the subset of all country codes that map to the non-geo entity region code.
597 countryCodesForNonGeographicalRegion.add(entry.getKey());
599 // The supported regions set does not include the "001" non-geo entity region code.
600 supportedRegions.addAll(regionCodes);
603 // If the non-geo entity still got added to the set of supported regions it must be because
604 // there are entries that list the non-geo entity alongside normal regions (which is wrong).
605 // If we discover this, remove the non-geo entity from the set of supported regions and log.
606 if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) {
607 logger.log(Level.WARNING, "invalid metadata " +
608 "(country calling code was mapped to the non-geo entity as well as specific region(s))");
610 nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
613 // @VisibleForTesting
614 void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode,
615 MetadataLoader metadataLoader) {
616 boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
617 String fileName = filePrefix + "_" +
618 (isNonGeoRegion ? String.valueOf(countryCallingCode) : regionCode);
619 InputStream source = metadataLoader.loadMetadata(fileName);
620 if (source == null) {
621 logger.log(Level.SEVERE, "missing metadata: " + fileName);
622 throw new IllegalStateException("missing metadata: " + fileName);
624 ObjectInputStream in = null;
626 in = new ObjectInputStream(source);
627 PhoneMetadataCollection metadataCollection = loadMetadataAndCloseInput(in);
628 List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
629 if (metadataList.isEmpty()) {
630 logger.log(Level.SEVERE, "empty metadata: " + fileName);
631 throw new IllegalStateException("empty metadata: " + fileName);
633 if (metadataList.size() > 1) {
634 logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName);
636 PhoneMetadata metadata = metadataList.get(0);
637 if (isNonGeoRegion) {
638 countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);
640 regionToMetadataMap.put(regionCode, metadata);
642 } catch (IOException e) {
643 logger.log(Level.SEVERE, "cannot load/parse metadata: " + fileName, e);
644 throw new RuntimeException("cannot load/parse metadata: " + fileName, e);
649 * Loads the metadata protocol buffer from the given stream and closes the stream afterwards. Any
650 * exceptions that occur while reading the stream are propagated (though exceptions that occur
651 * when the stream is closed will be ignored).
653 * @param source the non-null stream from which metadata is to be read.
654 * @return the loaded metadata protocol buffer.
656 private static PhoneMetadataCollection loadMetadataAndCloseInput(ObjectInputStream source) {
657 PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
659 metadataCollection.readExternal(source);
660 } catch (IOException e) {
661 logger.log(Level.WARNING, "error reading input (ignored)", e);
665 } catch (IOException e) {
666 logger.log(Level.WARNING, "error closing input stream (ignored)", e);
669 return metadataCollection;
673 * Attempts to extract a possible number from the string passed in. This currently strips all
674 * leading characters that cannot be used to start a phone number. Characters that can be used to
675 * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
676 * are found in the number passed in, an empty string is returned. This function also attempts to
677 * strip off any alternative extensions or endings if two or more are present, such as in the case
678 * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
679 * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
680 * number is parsed correctly.
682 * @param number the string that might contain a phone number
683 * @return the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
684 * string if no character used to start phone numbers (such as + or any digit) is
685 * found in the number
687 static String extractPossibleNumber(String number) {
688 Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
690 number = number.substring(m.start());
691 // Remove trailing non-alpha non-numerical characters.
692 Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
693 if (trailingCharsMatcher.find()) {
694 number = number.substring(0, trailingCharsMatcher.start());
695 logger.log(Level.FINER, "Stripped trailing characters: " + number);
697 // Check for extra numbers at the end.
698 Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
699 if (secondNumber.find()) {
700 number = number.substring(0, secondNumber.start());
709 * Checks to see if the string of characters could possibly be a phone number at all. At the
710 * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
711 * commonly found in phone numbers.
712 * This method does not require the number to be normalized in advance - but does assume that
713 * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
715 * @param number string to be checked for viability as a phone number
716 * @return true if the number could be a phone number of some sort, otherwise false
718 // @VisibleForTesting
719 static boolean isViablePhoneNumber(String number) {
720 if (number.length() < MIN_LENGTH_FOR_NSN) {
723 Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
728 * Normalizes a string of characters representing a phone number. This performs the following
730 * Punctuation is stripped.
731 * For ALPHA/VANITY numbers:
732 * Letters are converted to their numeric representation on a telephone keypad. The keypad
733 * used here is the one defined in ITU Recommendation E.161. This is only done if there are
734 * 3 or more letters in the number, to lessen the risk that such letters are typos.
736 * Wide-ascii digits are converted to normal ASCII (European) digits.
737 * Arabic-Indic numerals are converted to European numerals.
738 * Spurious alpha characters are stripped.
740 * @param number a string of characters representing a phone number
741 * @return the normalized string version of the phone number
743 static String normalize(String number) {
744 Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
746 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
748 return normalizeDigitsOnly(number);
753 * Normalizes a string of characters representing a phone number. This is a wrapper for
754 * normalize(String number) but does in-place normalization of the StringBuilder provided.
756 * @param number a StringBuilder of characters representing a phone number that will be
757 * normalized in place
759 static void normalize(StringBuilder number) {
760 String normalizedNumber = normalize(number.toString());
761 number.replace(0, number.length(), normalizedNumber);
765 * Normalizes a string of characters representing a phone number. This converts wide-ascii and
766 * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
768 * @param number a string of characters representing a phone number
769 * @return the normalized string version of the phone number
771 public static String normalizeDigitsOnly(String number) {
772 return normalizeDigits(number, false /* strip non-digits */).toString();
775 static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
776 StringBuilder normalizedDigits = new StringBuilder(number.length());
777 for (char c : number.toCharArray()) {
778 int digit = Character.digit(c, 10);
780 normalizedDigits.append(digit);
781 } else if (keepNonDigits) {
782 normalizedDigits.append(c);
785 return normalizedDigits;
789 * Normalizes a string of characters representing a phone number. This strips all characters which
790 * are not diallable on a mobile phone keypad (including all non-ASCII digits).
792 * @param number a string of characters representing a phone number
793 * @return the normalized string version of the phone number
795 static String normalizeDiallableCharsOnly(String number) {
796 return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
800 * Converts all alpha characters in a number to their respective digits on a keypad, but retains
801 * existing formatting.
803 public static String convertAlphaCharactersInNumber(String number) {
804 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
808 * Gets the length of the geographical area code from the
809 * PhoneNumber object passed in, so that clients could use it
810 * to split a national significant number into geographical area code and subscriber number. It
811 * works in such a way that the resultant subscriber number should be diallable, at least on some
812 * devices. An example of how this could be used:
815 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
816 * PhoneNumber number = phoneUtil.parse("16502530000", "US");
817 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
819 * String subscriberNumber;
821 * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
822 * if (areaCodeLength > 0) {
823 * areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
824 * subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
827 * subscriberNumber = nationalSignificantNumber;
831 * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
832 * using it for most purposes, but recommends using the more general {@code national_number}
833 * instead. Read the following carefully before deciding to use this method:
835 * <li> geographical area codes change over time, and this method honors those changes;
836 * therefore, it doesn't guarantee the stability of the result it produces.
837 * <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
838 * typically requires the full national_number to be dialled in most regions).
839 * <li> most non-geographical numbers have no area codes, including numbers from non-geographical
841 * <li> some geographical numbers have no area codes.
843 * @param number the PhoneNumber object for which clients
844 * want to know the length of the area code.
845 * @return the length of area code of the PhoneNumber object
848 public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
849 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
850 if (metadata == null) {
853 // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
854 // zero, we assume it is a closed dialling plan with no area codes.
855 if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) {
859 if (!isNumberGeographical(number)) {
863 return getLengthOfNationalDestinationCode(number);
867 * Gets the length of the national destination code (NDC) from the
868 * PhoneNumber object passed in, so that clients could use it
869 * to split a national significant number into NDC and subscriber number. The NDC of a phone
870 * number is normally the first group of digit(s) right after the country calling code when the
871 * number is formatted in the international format, if there is a subscriber number part that
872 * follows. An example of how this could be used:
875 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
876 * PhoneNumber number = phoneUtil.parse("18002530000", "US");
877 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
878 * String nationalDestinationCode;
879 * String subscriberNumber;
881 * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
882 * if (nationalDestinationCodeLength > 0) {
883 * nationalDestinationCode = nationalSignificantNumber.substring(0,
884 * nationalDestinationCodeLength);
885 * subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
887 * nationalDestinationCode = "";
888 * subscriberNumber = nationalSignificantNumber;
892 * Refer to the unittests to see the difference between this function and
893 * {@link #getLengthOfGeographicalAreaCode}.
895 * @param number the PhoneNumber object for which clients
896 * want to know the length of the NDC.
897 * @return the length of NDC of the PhoneNumber object
900 public int getLengthOfNationalDestinationCode(PhoneNumber number) {
901 PhoneNumber copiedProto;
902 if (number.hasExtension()) {
903 // We don't want to alter the proto given to us, but we don't want to include the extension
904 // when we format it, so we copy it and clear the extension here.
905 copiedProto = new PhoneNumber();
906 copiedProto.mergeFrom(number);
907 copiedProto.clearExtension();
909 copiedProto = number;
912 String nationalSignificantNumber = format(copiedProto,
913 PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
914 String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
915 // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
916 // string (before the + symbol) and the second group will be the country calling code. The third
917 // group will be area code if it is not the last group.
918 if (numberGroups.length <= 3) {
922 if (getNumberType(number) == PhoneNumberType.MOBILE) {
923 // For example Argentinian mobile numbers, when formatted in the international format, are in
924 // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
925 // add the length of the second group (which is the mobile token), which also forms part of
926 // the national significant number. This assumes that the mobile token is always formatted
927 // separately from the rest of the phone number.
928 String mobileToken = getCountryMobileToken(number.getCountryCode());
929 if (!mobileToken.equals("")) {
930 return numberGroups[2].length() + numberGroups[3].length();
933 return numberGroups[2].length();
937 * Returns the mobile token for the provided country calling code if it has one, otherwise
938 * returns an empty string. A mobile token is a number inserted before the area code when dialing
939 * a mobile number from that country from abroad.
941 * @param countryCallingCode the country calling code for which we want the mobile token
942 * @return the mobile token, as a string, for the given country calling code
944 public static String getCountryMobileToken(int countryCallingCode) {
945 if (MOBILE_TOKEN_MAPPINGS.containsKey(countryCallingCode)) {
946 return MOBILE_TOKEN_MAPPINGS.get(countryCallingCode);
952 * Normalizes a string of characters representing a phone number by replacing all characters found
953 * in the accompanying map with the values therein, and stripping all other characters if
954 * removeNonMatches is true.
956 * @param number a string of characters representing a phone number
957 * @param normalizationReplacements a mapping of characters to what they should be replaced by in
958 * the normalized version of the phone number
959 * @param removeNonMatches indicates whether characters that are not able to be replaced
960 * should be stripped from the number. If this is false, they
961 * will be left unchanged in the number.
962 * @return the normalized string version of the phone number
964 private static String normalizeHelper(String number,
965 Map<Character, Character> normalizationReplacements,
966 boolean removeNonMatches) {
967 StringBuilder normalizedNumber = new StringBuilder(number.length());
968 for (int i = 0; i < number.length(); i++) {
969 char character = number.charAt(i);
970 Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
971 if (newDigit != null) {
972 normalizedNumber.append(newDigit);
973 } else if (!removeNonMatches) {
974 normalizedNumber.append(character);
976 // If neither of the above are true, we remove this character.
978 return normalizedNumber.toString();
982 * Sets or resets the PhoneNumberUtil singleton instance. If set to null, the next call to
983 * {@code getInstance()} will load (and return) the default instance.
985 // @VisibleForTesting
986 static synchronized void setInstance(PhoneNumberUtil util) {
991 * Convenience method to get a list of what regions the library has metadata for.
993 public Set<String> getSupportedRegions() {
994 return Collections.unmodifiableSet(supportedRegions);
998 * Convenience method to get a list of what global network calling codes the library has metadata
1001 public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
1002 return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion);
1006 * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
1007 * parsing, or validation. The instance is loaded with phone number metadata for a number of most
1008 * commonly used regions.
1010 * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
1011 * multiple times will only result in one instance being created.
1013 * @return a PhoneNumberUtil instance
1015 public static synchronized PhoneNumberUtil getInstance() {
1016 if (instance == null) {
1017 setInstance(createInstance(DEFAULT_METADATA_LOADER));
1023 * Create a new {@link PhoneNumberUtil} instance to carry out international phone number
1024 * formatting, parsing, or validation. The instance is loaded with all metadata by
1025 * using the metadataLoader specified.
1027 * This method should only be used in the rare case in which you want to manage your own
1028 * metadata loading. Calling this method multiple times is very expensive, as each time
1029 * a new instance is created from scratch. When in doubt, use {@link #getInstance}.
1031 * @param metadataLoader Customized metadata loader. If null, default metadata loader will
1032 * be used. This should not be null.
1033 * @return a PhoneNumberUtil instance
1035 public static PhoneNumberUtil createInstance(MetadataLoader metadataLoader) {
1036 if (metadataLoader == null) {
1037 throw new IllegalArgumentException("metadataLoader could not be null.");
1039 return new PhoneNumberUtil(META_DATA_FILE_PREFIX, metadataLoader,
1040 CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
1044 * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
1045 * does not start with the national prefix.
1047 static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) {
1048 return nationalPrefixFormattingRule.length() == 0 ||
1049 FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches();
1053 * Tests whether a phone number has a geographical association. It checks if the number is
1054 * associated to a certain region in the country where it belongs to. Note that this doesn't
1055 * verify if the number is actually in use.
1057 * A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded, which performs a
1058 * looser check, since it only prevents cases where prefixes overlap for geocodable and
1059 * non-geocodable numbers. Also, if new phone number types were added, we should check if this
1060 * other method should be updated too.
1062 boolean isNumberGeographical(PhoneNumber phoneNumber) {
1063 PhoneNumberType numberType = getNumberType(phoneNumber);
1064 // TODO: Include mobile phone numbers from countries like Indonesia, which has some
1065 // mobile numbers that are geographical.
1066 return numberType == PhoneNumberType.FIXED_LINE ||
1067 numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
1071 * Helper function to check region code is not unknown or null.
1073 private boolean isValidRegionCode(String regionCode) {
1074 return regionCode != null && supportedRegions.contains(regionCode);
1078 * Helper function to check the country calling code is valid.
1080 private boolean hasValidCountryCallingCode(int countryCallingCode) {
1081 return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
1085 * Formats a phone number in the specified format using default rules. Note that this does not
1086 * promise to produce a phone number that the user can dial from where they are - although we do
1087 * format in either 'national' or 'international' format depending on what the client asks for, we
1088 * do not currently support a more abbreviated format, such as for users in the same "area" who
1089 * could potentially dial the number without area code. Note that if the phone number has a
1090 * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1091 * which formatting rules to apply so we return the national significant number with no formatting
1094 * @param number the phone number to be formatted
1095 * @param numberFormat the format the phone number should be formatted into
1096 * @return the formatted phone number
1098 public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
1099 if (number.getNationalNumber() == 0 && number.hasRawInput()) {
1100 // Unparseable numbers that kept their raw input just use that.
1101 // This is the only case where a number can be formatted as E164 without a
1102 // leading '+' symbol (but the original number wasn't parseable anyway).
1103 // TODO: Consider removing the 'if' above so that unparseable
1104 // strings without raw input format to the empty string instead of "+00"
1105 String rawInput = number.getRawInput();
1106 if (rawInput.length() > 0) {
1110 StringBuilder formattedNumber = new StringBuilder(20);
1111 format(number, numberFormat, formattedNumber);
1112 return formattedNumber.toString();
1116 * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
1117 * a parameter to decrease object creation when invoked many times.
1119 public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1120 StringBuilder formattedNumber) {
1121 // Clear the StringBuilder first.
1122 formattedNumber.setLength(0);
1123 int countryCallingCode = number.getCountryCode();
1124 String nationalSignificantNumber = getNationalSignificantNumber(number);
1126 if (numberFormat == PhoneNumberFormat.E164) {
1127 // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1128 // of the national number needs to be applied. Extensions are not formatted.
1129 formattedNumber.append(nationalSignificantNumber);
1130 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1134 if (!hasValidCountryCallingCode(countryCallingCode)) {
1135 formattedNumber.append(nationalSignificantNumber);
1138 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1139 // share a country calling code is contained by only one region for performance reasons. For
1140 // example, for NANPA regions it will be contained in the metadata for US.
1141 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1142 // Metadata cannot be null because the country calling code is valid (which means that the
1143 // region code cannot be ZZ and must be one of our supported region codes).
1144 PhoneMetadata metadata =
1145 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1146 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1147 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1148 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1152 * Formats a phone number in the specified format using client-defined formatting rules. Note that
1153 * if the phone number has a country calling code of zero or an otherwise invalid country calling
1154 * code, we cannot work out things like whether there should be a national prefix applied, or how
1155 * to format extensions, so we return the national significant number with no formatting applied.
1157 * @param number the phone number to be formatted
1158 * @param numberFormat the format the phone number should be formatted into
1159 * @param userDefinedFormats formatting rules specified by clients
1160 * @return the formatted phone number
1162 public String formatByPattern(PhoneNumber number,
1163 PhoneNumberFormat numberFormat,
1164 List<NumberFormat> userDefinedFormats) {
1165 int countryCallingCode = number.getCountryCode();
1166 String nationalSignificantNumber = getNationalSignificantNumber(number);
1167 if (!hasValidCountryCallingCode(countryCallingCode)) {
1168 return nationalSignificantNumber;
1170 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1171 // share a country calling code is contained by only one region for performance reasons. For
1172 // example, for NANPA regions it will be contained in the metadata for US.
1173 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1174 // Metadata cannot be null because the country calling code is valid
1175 PhoneMetadata metadata =
1176 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1178 StringBuilder formattedNumber = new StringBuilder(20);
1180 NumberFormat formattingPattern =
1181 chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1182 if (formattingPattern == null) {
1183 // If no pattern above is matched, we format the number as a whole.
1184 formattedNumber.append(nationalSignificantNumber);
1186 NumberFormat numFormatCopy = new NumberFormat();
1187 // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1188 // need to copy the rule so that subsequent replacements for different numbers have the
1189 // appropriate national prefix.
1190 numFormatCopy.mergeFrom(formattingPattern);
1191 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1192 if (nationalPrefixFormattingRule.length() > 0) {
1193 String nationalPrefix = metadata.getNationalPrefix();
1194 if (nationalPrefix.length() > 0) {
1195 // Replace $NP with national prefix and $FG with the first group ($1).
1196 nationalPrefixFormattingRule =
1197 NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
1198 nationalPrefixFormattingRule =
1199 FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
1200 numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1202 // We don't want to have a rule for how to format the national prefix if there isn't one.
1203 numFormatCopy.clearNationalPrefixFormattingRule();
1206 formattedNumber.append(
1207 formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
1209 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1210 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1211 return formattedNumber.toString();
1215 * Formats a phone number in national format for dialing using the carrier as specified in the
1216 * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1217 * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1218 * contains an empty string, returns the number in national format without any carrier code.
1220 * @param number the phone number to be formatted
1221 * @param carrierCode the carrier selection code to be used
1222 * @return the formatted phone number in national format for dialing using the carrier as
1223 * specified in the {@code carrierCode}
1225 public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
1226 int countryCallingCode = number.getCountryCode();
1227 String nationalSignificantNumber = getNationalSignificantNumber(number);
1228 if (!hasValidCountryCallingCode(countryCallingCode)) {
1229 return nationalSignificantNumber;
1232 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1233 // share a country calling code is contained by only one region for performance reasons. For
1234 // example, for NANPA regions it will be contained in the metadata for US.
1235 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1236 // Metadata cannot be null because the country calling code is valid.
1237 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1239 StringBuilder formattedNumber = new StringBuilder(20);
1240 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1241 PhoneNumberFormat.NATIONAL, carrierCode));
1242 maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1243 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1245 return formattedNumber.toString();
1248 private PhoneMetadata getMetadataForRegionOrCallingCode(
1249 int countryCallingCode, String regionCode) {
1250 return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1251 ? getMetadataForNonGeographicalRegion(countryCallingCode)
1252 : getMetadataForRegion(regionCode);
1256 * Formats a phone number in national format for dialing using the carrier as specified in the
1257 * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1258 * use the {@code fallbackCarrierCode} passed in instead. If there is no
1259 * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1260 * string, return the number in national format without any carrier code.
1262 * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1263 * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
1265 * @param number the phone number to be formatted
1266 * @param fallbackCarrierCode the carrier selection code to be used, if none is found in the
1267 * phone number itself
1268 * @return the formatted phone number in national format for dialing using the number's
1269 * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1272 public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
1273 String fallbackCarrierCode) {
1274 return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
1275 ? number.getPreferredDomesticCarrierCode()
1276 : fallbackCarrierCode);
1280 * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1281 * specific region. If the number cannot be reached from the region (e.g. some countries block
1282 * toll-free numbers from being called outside of the country), the method returns an empty
1285 * @param number the phone number to be formatted
1286 * @param regionCallingFrom the region where the call is being placed
1287 * @param withFormatting whether the number should be returned with formatting symbols, such as
1288 * spaces and dashes.
1289 * @return the formatted phone number
1291 public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1292 boolean withFormatting) {
1293 int countryCallingCode = number.getCountryCode();
1294 if (!hasValidCountryCallingCode(countryCallingCode)) {
1295 return number.hasRawInput() ? number.getRawInput() : "";
1298 String formattedNumber = "";
1299 // Clear the extension, as that part cannot normally be dialed together with the main number.
1300 PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1301 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1302 PhoneNumberType numberType = getNumberType(numberNoExt);
1303 boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN);
1304 if (regionCallingFrom.equals(regionCode)) {
1305 boolean isFixedLineOrMobile =
1306 (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
1307 (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1308 // Carrier codes may be needed in some countries. We handle this here.
1309 if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
1311 formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
1312 } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
1313 formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
1314 ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1315 // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1316 // called within Brazil. Without that, most of the carriers won't connect the call.
1317 // Because of that, we return an empty string here.
1319 } else if (isValidNumber && regionCode.equals("HU")) {
1320 // The national format for HU numbers doesn't contain the national prefix, because that is
1321 // how numbers are normally written down. However, the national prefix is obligatory when
1322 // dialing from a mobile phone, except for short numbers. As a result, we add it back here
1323 // if it is a valid regular length phone number.
1325 getNddPrefixForRegion(regionCode, true /* strip non-digits */) +
1326 " " + format(numberNoExt, PhoneNumberFormat.NATIONAL);
1327 } else if (countryCallingCode == NANPA_COUNTRY_CODE) {
1328 // For NANPA countries, we output international format for numbers that can be dialed
1329 // internationally, since that always works, except for numbers which might potentially be
1330 // short numbers, which are always dialled in national format.
1331 PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom);
1332 if (canBeInternationallyDialled(numberNoExt) &&
1333 !isShorterThanPossibleNormalNumber(regionMetadata,
1334 getNationalSignificantNumber(numberNoExt))) {
1335 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1337 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1340 // For non-geographical countries, and Mexican and Chilean fixed line and mobile numbers, we
1341 // output international format for numbers that can be dialed internationally as that always
1343 if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
1344 // MX fixed line and mobile numbers should always be formatted in international format,
1345 // even when dialed within MX. For national format to work, a carrier code needs to be
1346 // used, and the correct carrier code depends on if the caller and callee are from the
1347 // same local area. It is trickier to get that to work correctly than using
1348 // international format, which is tested to work fine on all carriers.
1349 // CL fixed line numbers need the national prefix when dialing in the national format,
1350 // but don't have it when used for display. The reverse is true for mobile numbers.
1351 // As a result, we output them in the international format to make it work.
1352 ((regionCode.equals("MX") || regionCode.equals("CL")) &&
1353 isFixedLineOrMobile)) &&
1354 canBeInternationallyDialled(numberNoExt)) {
1355 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1357 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1360 } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) {
1361 // We assume that short numbers are not diallable from outside their region, so if a number
1362 // is not a valid regular length phone number, we treat it as if it cannot be internationally
1364 return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1365 : format(numberNoExt, PhoneNumberFormat.E164);
1367 return withFormatting ? formattedNumber
1368 : normalizeDiallableCharsOnly(formattedNumber);
1372 * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1373 * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1374 * same as that of the region where the number is from, then NATIONAL formatting will be applied.
1376 * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1377 * calling code, then we return the number with no formatting applied.
1379 * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1380 * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1381 * is used. For regions which have multiple international prefixes, the number in its
1382 * INTERNATIONAL format will be returned instead.
1384 * @param number the phone number to be formatted
1385 * @param regionCallingFrom the region where the call is being placed
1386 * @return the formatted phone number
1388 public String formatOutOfCountryCallingNumber(PhoneNumber number,
1389 String regionCallingFrom) {
1390 if (!isValidRegionCode(regionCallingFrom)) {
1391 logger.log(Level.WARNING,
1392 "Trying to format number from invalid region "
1394 + ". International formatting applied.");
1395 return format(number, PhoneNumberFormat.INTERNATIONAL);
1397 int countryCallingCode = number.getCountryCode();
1398 String nationalSignificantNumber = getNationalSignificantNumber(number);
1399 if (!hasValidCountryCallingCode(countryCallingCode)) {
1400 return nationalSignificantNumber;
1402 if (countryCallingCode == NANPA_COUNTRY_CODE) {
1403 if (isNANPACountry(regionCallingFrom)) {
1404 // For NANPA regions, return the national format for these regions but prefix it with the
1405 // country calling code.
1406 return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
1408 } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1409 // If regions share a country calling code, the country calling code need not be dialled.
1410 // This also applies when dialling within a region, so this if clause covers both these cases.
1411 // Technically this is the case for dialling from La Reunion to other overseas departments of
1412 // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
1413 // edge case for now and for those cases return the version including country calling code.
1414 // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
1415 return format(number, PhoneNumberFormat.NATIONAL);
1417 // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1418 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1419 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1421 // For regions that have multiple international prefixes, the international format of the
1422 // number is returned, unless there is a preferred international prefix.
1423 String internationalPrefixForFormatting = "";
1424 if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
1425 internationalPrefixForFormatting = internationalPrefix;
1426 } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1427 internationalPrefixForFormatting =
1428 metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1431 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1432 // Metadata cannot be null because the country calling code is valid.
1433 PhoneMetadata metadataForRegion =
1434 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1435 String formattedNationalNumber =
1436 formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1437 StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1438 maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1440 if (internationalPrefixForFormatting.length() > 0) {
1441 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1442 .insert(0, internationalPrefixForFormatting);
1444 prefixNumberWithCountryCallingCode(countryCallingCode,
1445 PhoneNumberFormat.INTERNATIONAL,
1448 return formattedNumber.toString();
1452 * Formats a phone number using the original phone number format that the number is parsed from.
1453 * The original format is embedded in the country_code_source field of the PhoneNumber object
1454 * passed in. If such information is missing, the number will be formatted into the NATIONAL
1455 * format by default. When the number contains a leading zero and this is unexpected for this
1456 * country, or we don't have a formatting pattern for the number, the method returns the raw input
1457 * when it is available.
1459 * Note this method guarantees no digit will be inserted, removed or modified as a result of
1462 * @param number the phone number that needs to be formatted in its original number format
1463 * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number
1465 * @return the formatted phone number in its original number format
1467 public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
1468 if (number.hasRawInput() &&
1469 (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
1470 // We check if we have the formatting pattern because without that, we might format the number
1471 // as a group without national prefix.
1472 return number.getRawInput();
1474 if (!number.hasCountryCodeSource()) {
1475 return format(number, PhoneNumberFormat.NATIONAL);
1477 String formattedNumber;
1478 switch (number.getCountryCodeSource()) {
1479 case FROM_NUMBER_WITH_PLUS_SIGN:
1480 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1482 case FROM_NUMBER_WITH_IDD:
1483 formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1485 case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1486 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1488 case FROM_DEFAULT_COUNTRY:
1489 // Fall-through to default case.
1491 String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1492 // We strip non-digits from the NDD here, and from the raw input later, so that we can
1493 // compare them easily.
1494 String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1495 String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1496 if (nationalPrefix == null || nationalPrefix.length() == 0) {
1497 // If the region doesn't have a national prefix at all, we can safely return the national
1498 // format without worrying about a national prefix being added.
1499 formattedNumber = nationalFormat;
1502 // Otherwise, we check if the original number was entered with a national prefix.
1503 if (rawInputContainsNationalPrefix(
1504 number.getRawInput(), nationalPrefix, regionCode)) {
1505 // If so, we can safely return the national format.
1506 formattedNumber = nationalFormat;
1509 // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1510 // there is no metadata for the region.
1511 PhoneMetadata metadata = getMetadataForRegion(regionCode);
1512 String nationalNumber = getNationalSignificantNumber(number);
1513 NumberFormat formatRule =
1514 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1515 // The format rule could still be null here if the national number was 0 and there was no
1516 // raw input (this should not be possible for numbers generated by the phonenumber library
1517 // as they would also not have a country calling code and we would have exited earlier).
1518 if (formatRule == null) {
1519 formattedNumber = nationalFormat;
1522 // When the format we apply to this number doesn't contain national prefix, we can just
1523 // return the national format.
1524 // TODO: Refactor the code below with the code in
1525 // isNationalPrefixPresentIfRequired.
1526 String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1527 // We assume that the first-group symbol will never be _before_ the national prefix.
1528 int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1529 if (indexOfFirstGroup <= 0) {
1530 formattedNumber = nationalFormat;
1533 candidateNationalPrefixRule =
1534 candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1535 candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1536 if (candidateNationalPrefixRule.length() == 0) {
1537 // National prefix not used when formatting this number.
1538 formattedNumber = nationalFormat;
1541 // Otherwise, we need to remove the national prefix from our output.
1542 NumberFormat numFormatCopy = new NumberFormat();
1543 numFormatCopy.mergeFrom(formatRule);
1544 numFormatCopy.clearNationalPrefixFormattingRule();
1545 List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
1546 numberFormats.add(numFormatCopy);
1547 formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1550 String rawInput = number.getRawInput();
1551 // If no digit is inserted/removed/modified as a result of our formatting, we return the
1552 // formatted phone number; otherwise we return the raw input the user entered.
1553 if (formattedNumber != null && rawInput.length() > 0) {
1554 String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1555 String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1556 if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1557 formattedNumber = rawInput;
1560 return formattedNumber;
1563 // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1564 // national prefix is assumed to be in digits-only form.
1565 private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1566 String regionCode) {
1567 String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1568 if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1570 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1571 // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1572 // check the validity of the number if the assumed national prefix is removed (777123 won't
1573 // be valid in Japan).
1574 return isValidNumber(
1575 parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1576 } catch (NumberParseException e) {
1584 * Returns true if a number is from a region whose national significant number couldn't contain a
1585 * leading zero, but has the italian_leading_zero field set to true.
1587 private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
1588 return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
1591 private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1592 int countryCallingCode = number.getCountryCode();
1593 String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1594 PhoneMetadata metadata =
1595 getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
1596 if (metadata == null) {
1599 String nationalNumber = getNationalSignificantNumber(number);
1600 NumberFormat formatRule =
1601 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1602 return formatRule != null;
1606 * Formats a phone number for out-of-country dialing purposes.
1608 * Note that in this version, if the number was entered originally using alpha characters and
1609 * this version of the number is stored in raw_input, this representation of the number will be
1610 * used rather than the digit representation. Grouping information, as specified by characters
1611 * such as "-" and " ", will be retained.
1613 * <p><b>Caveats:</b></p>
1615 * <li> This will not produce good results if the country calling code is both present in the raw
1616 * input _and_ is the start of the national number. This is not a problem in the regions
1617 * which typically use alpha numbers.
1618 * <li> This will also not produce good results if the raw input has any grouping information
1619 * within the first three digits of the national number, and if the function needs to strip
1620 * preceding digits/words in the raw input before these digits. Normally people group the
1621 * first three digits together so this is not a huge problem - and will be fixed if it
1625 * @param number the phone number that needs to be formatted
1626 * @param regionCallingFrom the region where the call is being placed
1627 * @return the formatted phone number
1629 public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1630 String regionCallingFrom) {
1631 String rawInput = number.getRawInput();
1632 // If there is no raw input, then we can't keep alpha characters because there aren't any.
1633 // In this case, we return formatOutOfCountryCallingNumber.
1634 if (rawInput.length() == 0) {
1635 return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1637 int countryCode = number.getCountryCode();
1638 if (!hasValidCountryCallingCode(countryCode)) {
1641 // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1642 // the number in raw_input with the parsed number.
1643 // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1645 rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1646 // Now we trim everything before the first three digits in the parsed number. We choose three
1647 // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1648 // trim anything at all. Similarly, if the national number was less than three digits, we don't
1649 // trim anything at all.
1650 String nationalNumber = getNationalSignificantNumber(number);
1651 if (nationalNumber.length() > 3) {
1652 int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1653 if (firstNationalNumberDigit != -1) {
1654 rawInput = rawInput.substring(firstNationalNumberDigit);
1657 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1658 if (countryCode == NANPA_COUNTRY_CODE) {
1659 if (isNANPACountry(regionCallingFrom)) {
1660 return countryCode + " " + rawInput;
1662 } else if (metadataForRegionCallingFrom != null &&
1663 countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1664 NumberFormat formattingPattern =
1665 chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
1667 if (formattingPattern == null) {
1668 // If no pattern above is matched, we format the original input.
1671 NumberFormat newFormat = new NumberFormat();
1672 newFormat.mergeFrom(formattingPattern);
1673 // The first group is the first group of digits that the user wrote together.
1674 newFormat.setPattern("(\\d+)(.*)");
1675 // Here we just concatenate them back together after the national prefix has been fixed.
1676 newFormat.setFormat("$1$2");
1677 // Now we format using this pattern instead of the default pattern, but with the national
1678 // prefix prefixed if necessary.
1679 // This will not work in the cases where the pattern (and not the leading digits) decide
1680 // whether a national prefix needs to be used, since we have overridden the pattern to match
1681 // anything, but that is not the case in the metadata to date.
1682 return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
1684 String internationalPrefixForFormatting = "";
1685 // If an unsupported region-calling-from is entered, or a country with multiple international
1686 // prefixes, the international format of the number is returned, unless there is a preferred
1687 // international prefix.
1688 if (metadataForRegionCallingFrom != null) {
1689 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1690 internationalPrefixForFormatting =
1691 UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1692 ? internationalPrefix
1693 : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1695 StringBuilder formattedNumber = new StringBuilder(rawInput);
1696 String regionCode = getRegionCodeForCountryCode(countryCode);
1697 // Metadata cannot be null because the country calling code is valid.
1698 PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1699 maybeAppendFormattedExtension(number, metadataForRegion,
1700 PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1701 if (internationalPrefixForFormatting.length() > 0) {
1702 formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1703 .insert(0, internationalPrefixForFormatting);
1705 // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1706 // region chosen has multiple international dialling prefixes.
1707 logger.log(Level.WARNING,
1708 "Trying to format number from invalid region "
1710 + ". International formatting applied.");
1711 prefixNumberWithCountryCallingCode(countryCode,
1712 PhoneNumberFormat.INTERNATIONAL,
1715 return formattedNumber.toString();
1719 * Gets the national significant number of the a phone number. Note a national significant number
1720 * doesn't contain a national prefix or any formatting.
1722 * @param number the phone number for which the national significant number is needed
1723 * @return the national significant number of the PhoneNumber object passed in
1725 public String getNationalSignificantNumber(PhoneNumber number) {
1726 // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
1727 StringBuilder nationalNumber = new StringBuilder();
1728 if (number.isItalianLeadingZero()) {
1729 char[] zeros = new char[number.getNumberOfLeadingZeros()];
1730 Arrays.fill(zeros, '0');
1731 nationalNumber.append(new String(zeros));
1733 nationalNumber.append(number.getNationalNumber());
1734 return nationalNumber.toString();
1738 * A helper function that is used by format and formatByPattern.
1740 private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1741 PhoneNumberFormat numberFormat,
1742 StringBuilder formattedNumber) {
1743 switch (numberFormat) {
1745 formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1748 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1751 formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1752 .insert(0, RFC3966_PREFIX);
1760 // Simple wrapper of formatNsn for the common case of no carrier code.
1761 private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1762 return formatNsn(number, metadata, numberFormat, null);
1765 // Note in some regions, the national number can be written in two completely different ways
1766 // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1767 // numberFormat parameter here is used to specify which format to use for those cases. If a
1768 // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1769 private String formatNsn(String number,
1770 PhoneMetadata metadata,
1771 PhoneNumberFormat numberFormat,
1772 String carrierCode) {
1773 List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
1774 // When the intlNumberFormats exists, we use that to format national number for the
1775 // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1776 List<NumberFormat> availableFormats =
1777 (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
1778 ? metadata.numberFormats()
1779 : metadata.intlNumberFormats();
1780 NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1781 return (formattingPattern == null)
1783 : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
1786 NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1787 String nationalNumber) {
1788 for (NumberFormat numFormat : availableFormats) {
1789 int size = numFormat.leadingDigitsPatternSize();
1790 if (size == 0 || regexCache.getPatternForRegex(
1791 // We always use the last leading_digits_pattern, as it is the most detailed.
1792 numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
1793 Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1802 // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1803 String formatNsnUsingPattern(String nationalNumber,
1804 NumberFormat formattingPattern,
1805 PhoneNumberFormat numberFormat) {
1806 return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
1809 // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1811 private String formatNsnUsingPattern(String nationalNumber,
1812 NumberFormat formattingPattern,
1813 PhoneNumberFormat numberFormat,
1814 String carrierCode) {
1815 String numberFormatRule = formattingPattern.getFormat();
1817 regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1818 String formattedNationalNumber = "";
1819 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1820 carrierCode != null && carrierCode.length() > 0 &&
1821 formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1822 // Replace the $CC in the formatting rule with the desired carrier code.
1823 String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1824 carrierCodeFormattingRule =
1825 CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
1826 // Now replace the $FG in the formatting rule with the first group and the carrier code
1827 // combined in the appropriate way.
1828 numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
1829 .replaceFirst(carrierCodeFormattingRule);
1830 formattedNationalNumber = m.replaceAll(numberFormatRule);
1832 // Use the national prefix formatting rule instead.
1833 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1834 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1835 nationalPrefixFormattingRule != null &&
1836 nationalPrefixFormattingRule.length() > 0) {
1837 Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
1838 formattedNationalNumber =
1839 m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
1841 formattedNationalNumber = m.replaceAll(numberFormatRule);
1844 if (numberFormat == PhoneNumberFormat.RFC3966) {
1845 // Strip any leading punctuation.
1846 Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
1847 if (matcher.lookingAt()) {
1848 formattedNationalNumber = matcher.replaceFirst("");
1850 // Replace the rest with a dash between each number group.
1851 formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
1853 return formattedNationalNumber;
1857 * Gets a valid number for the specified region.
1859 * @param regionCode the region for which an example number is needed
1860 * @return a valid fixed-line number for the specified region. Returns null when the metadata
1861 * does not contain such information, or the region 001 is passed in. For 001 (representing
1862 * non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
1864 public PhoneNumber getExampleNumber(String regionCode) {
1865 return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
1869 * Gets a valid number for the specified region and number type.
1871 * @param regionCode the region for which an example number is needed
1872 * @param type the type of number that is needed
1873 * @return a valid number for the specified region and type. Returns null when the metadata
1874 * does not contain such information or if an invalid region or region 001 was entered.
1875 * For 001 (representing non-geographical numbers), call
1876 * {@link #getExampleNumberForNonGeoEntity} instead.
1878 public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
1879 // Check the region code is valid.
1880 if (!isValidRegionCode(regionCode)) {
1881 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
1884 PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
1886 if (desc.hasExampleNumber()) {
1887 return parse(desc.getExampleNumber(), regionCode);
1889 } catch (NumberParseException e) {
1890 logger.log(Level.SEVERE, e.toString());
1896 * Gets a valid number for the specified country calling code for a non-geographical entity.
1898 * @param countryCallingCode the country calling code for a non-geographical entity
1899 * @return a valid number for the non-geographical entity. Returns null when the metadata
1900 * does not contain such information, or the country calling code passed in does not belong
1901 * to a non-geographical entity.
1903 public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
1904 PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
1905 if (metadata != null) {
1906 PhoneNumberDesc desc = metadata.getGeneralDesc();
1908 if (desc.hasExampleNumber()) {
1909 return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
1911 } catch (NumberParseException e) {
1912 logger.log(Level.SEVERE, e.toString());
1915 logger.log(Level.WARNING,
1916 "Invalid or unknown country calling code provided: " + countryCallingCode);
1922 * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1923 * an extension specified.
1925 private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
1926 PhoneNumberFormat numberFormat,
1927 StringBuilder formattedNumber) {
1928 if (number.hasExtension() && number.getExtension().length() > 0) {
1929 if (numberFormat == PhoneNumberFormat.RFC3966) {
1930 formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
1932 if (metadata.hasPreferredExtnPrefix()) {
1933 formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
1935 formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
1941 PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
1944 return metadata.getPremiumRate();
1946 return metadata.getTollFree();
1948 return metadata.getMobile();
1950 case FIXED_LINE_OR_MOBILE:
1951 return metadata.getFixedLine();
1953 return metadata.getSharedCost();
1955 return metadata.getVoip();
1956 case PERSONAL_NUMBER:
1957 return metadata.getPersonalNumber();
1959 return metadata.getPager();
1961 return metadata.getUan();
1963 return metadata.getVoicemail();
1965 return metadata.getGeneralDesc();
1970 * Gets the type of a phone number.
1972 * @param number the phone number that we want to know the type
1973 * @return the type of the phone number
1975 public PhoneNumberType getNumberType(PhoneNumber number) {
1976 String regionCode = getRegionCodeForNumber(number);
1977 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
1978 if (metadata == null) {
1979 return PhoneNumberType.UNKNOWN;
1981 String nationalSignificantNumber = getNationalSignificantNumber(number);
1982 return getNumberTypeHelper(nationalSignificantNumber, metadata);
1985 private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
1986 if (!isNumberMatchingDesc(nationalNumber, metadata.getGeneralDesc())) {
1987 return PhoneNumberType.UNKNOWN;
1990 if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
1991 return PhoneNumberType.PREMIUM_RATE;
1993 if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
1994 return PhoneNumberType.TOLL_FREE;
1996 if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
1997 return PhoneNumberType.SHARED_COST;
1999 if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
2000 return PhoneNumberType.VOIP;
2002 if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
2003 return PhoneNumberType.PERSONAL_NUMBER;
2005 if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
2006 return PhoneNumberType.PAGER;
2008 if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
2009 return PhoneNumberType.UAN;
2011 if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
2012 return PhoneNumberType.VOICEMAIL;
2015 boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
2017 if (metadata.isSameMobileAndFixedLinePattern()) {
2018 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2019 } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2020 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2022 return PhoneNumberType.FIXED_LINE;
2024 // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
2025 // mobile and fixed line aren't the same.
2026 if (!metadata.isSameMobileAndFixedLinePattern() &&
2027 isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2028 return PhoneNumberType.MOBILE;
2030 return PhoneNumberType.UNKNOWN;
2034 * Returns the metadata for the given region code or {@code null} if the region code is invalid
2037 PhoneMetadata getMetadataForRegion(String regionCode) {
2038 if (!isValidRegionCode(regionCode)) {
2041 synchronized (regionToMetadataMap) {
2042 if (!regionToMetadataMap.containsKey(regionCode)) {
2043 // The regionCode here will be valid and won't be '001', so we don't need to worry about
2044 // what to pass in for the country calling code.
2045 loadMetadataFromFile(currentFilePrefix, regionCode, 0, metadataLoader);
2048 return regionToMetadataMap.get(regionCode);
2051 PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
2052 synchronized (countryCodeToNonGeographicalMetadataMap) {
2053 if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
2056 if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
2057 loadMetadataFromFile(
2058 currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode, metadataLoader);
2061 return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
2064 boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2065 Matcher possibleNumberPatternMatcher =
2066 regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
2067 .matcher(nationalNumber);
2068 return possibleNumberPatternMatcher.matches();
2071 boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2072 Matcher nationalNumberPatternMatcher =
2073 regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
2074 .matcher(nationalNumber);
2075 return isNumberPossibleForDesc(nationalNumber, numberDesc) &&
2076 nationalNumberPatternMatcher.matches();
2080 * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2081 * is actually in use, which is impossible to tell by just looking at a number itself.
2083 * @param number the phone number that we want to validate
2084 * @return a boolean that indicates whether the number is of a valid pattern
2086 public boolean isValidNumber(PhoneNumber number) {
2087 String regionCode = getRegionCodeForNumber(number);
2088 return isValidNumberForRegion(number, regionCode);
2092 * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2093 * is actually in use, which is impossible to tell by just looking at a number itself. If the
2094 * country calling code is not the same as the country calling code for the region, this
2095 * immediately exits with false. After this, the specific number pattern rules for the region are
2096 * examined. This is useful for determining for example whether a particular number is valid for
2097 * Canada, rather than just a valid NANPA number.
2098 * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2099 * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2100 * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2103 * @param number the phone number that we want to validate
2104 * @param regionCode the region that we want to validate the phone number for
2105 * @return a boolean that indicates whether the number is of a valid pattern
2107 public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2108 int countryCode = number.getCountryCode();
2109 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2110 if ((metadata == null) ||
2111 (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
2112 countryCode != getCountryCodeForValidRegion(regionCode))) {
2113 // Either the region code was invalid, or the country calling code for this number does not
2114 // match that of the region code.
2117 String nationalSignificantNumber = getNationalSignificantNumber(number);
2118 return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
2122 * Returns the region where a phone number is from. This could be used for geocoding at the region
2125 * @param number the phone number whose origin we want to know
2126 * @return the region where the phone number is from, or null if no region matches this calling
2129 public String getRegionCodeForNumber(PhoneNumber number) {
2130 int countryCode = number.getCountryCode();
2131 List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
2132 if (regions == null) {
2133 String numberString = getNationalSignificantNumber(number);
2134 logger.log(Level.WARNING,
2135 "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
2138 if (regions.size() == 1) {
2139 return regions.get(0);
2141 return getRegionCodeForNumberFromRegionList(number, regions);
2145 private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
2146 List<String> regionCodes) {
2147 String nationalNumber = getNationalSignificantNumber(number);
2148 for (String regionCode : regionCodes) {
2149 // If leadingDigits is present, use this. Otherwise, do full validation.
2150 // Metadata cannot be null because the region codes come from the country calling code map.
2151 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2152 if (metadata.hasLeadingDigits()) {
2153 if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
2154 .matcher(nationalNumber).lookingAt()) {
2157 } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
2165 * Returns the region code that matches the specific country calling code. In the case of no
2166 * region code being found, ZZ will be returned. In the case of multiple regions, the one
2167 * designated in the metadata as the "main" region for this calling code will be returned. If the
2168 * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
2169 * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
2170 * the value for World in the UN M.49 schema).
2172 public String getRegionCodeForCountryCode(int countryCallingCode) {
2173 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2174 return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
2178 * Returns a list with the region codes that match the specific country calling code. For
2179 * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2180 * of no region code being found, an empty list is returned.
2182 public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2183 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2184 return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2189 * Returns the country calling code for a specific region. For example, this would be 1 for the
2190 * United States, and 64 for New Zealand.
2192 * @param regionCode the region that we want to get the country calling code for
2193 * @return the country calling code for the region denoted by regionCode
2195 public int getCountryCodeForRegion(String regionCode) {
2196 if (!isValidRegionCode(regionCode)) {
2197 logger.log(Level.WARNING,
2198 "Invalid or missing region code ("
2199 + ((regionCode == null) ? "null" : regionCode)
2203 return getCountryCodeForValidRegion(regionCode);
2207 * Returns the country calling code for a specific region. For example, this would be 1 for the
2208 * United States, and 64 for New Zealand. Assumes the region is already valid.
2210 * @param regionCode the region that we want to get the country calling code for
2211 * @return the country calling code for the region denoted by regionCode
2212 * @throws IllegalArgumentException if the region is invalid
2214 private int getCountryCodeForValidRegion(String regionCode) {
2215 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2216 if (metadata == null) {
2217 throw new IllegalArgumentException("Invalid region code: " + regionCode);
2219 return metadata.getCountryCode();
2223 * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2224 * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2225 * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2226 * present, we return null.
2228 * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2229 * national dialling prefix is used only for certain types of numbers. Use the library's
2230 * formatting functions to prefix the national prefix when required.
2232 * @param regionCode the region that we want to get the dialling prefix for
2233 * @param stripNonDigits true to strip non-digits from the national dialling prefix
2234 * @return the dialling prefix for the region denoted by regionCode
2236 public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2237 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2238 if (metadata == null) {
2239 logger.log(Level.WARNING,
2240 "Invalid or missing region code ("
2241 + ((regionCode == null) ? "null" : regionCode)
2245 String nationalPrefix = metadata.getNationalPrefix();
2246 // If no national prefix was found, we return null.
2247 if (nationalPrefix.length() == 0) {
2250 if (stripNonDigits) {
2251 // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2252 // to be removed here as well.
2253 nationalPrefix = nationalPrefix.replace("~", "");
2255 return nationalPrefix;
2259 * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2261 * @return true if regionCode is one of the regions under NANPA
2263 public boolean isNANPACountry(String regionCode) {
2264 return nanpaRegions.contains(regionCode);
2268 * Checks whether the country calling code is from a region whose national significant number
2269 * could contain a leading zero. An example of such a region is Italy. Returns false if no
2270 * metadata for the country is found.
2272 boolean isLeadingZeroPossible(int countryCallingCode) {
2273 PhoneMetadata mainMetadataForCallingCode =
2274 getMetadataForRegionOrCallingCode(countryCallingCode,
2275 getRegionCodeForCountryCode(countryCallingCode));
2276 if (mainMetadataForCallingCode == null) {
2279 return mainMetadataForCallingCode.isLeadingZeroPossible();
2283 * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2284 * number will start with at least 3 digits and will have three or more alpha characters. This
2285 * does not do region-specific checks - to work out if this number is actually valid for a region,
2286 * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2287 * {@link #isValidNumber} should be used.
2289 * @param number the number that needs to be checked
2290 * @return true if the number is a valid vanity number
2292 public boolean isAlphaNumber(String number) {
2293 if (!isViablePhoneNumber(number)) {
2294 // Number is too short, or doesn't match the basic phone number pattern.
2297 StringBuilder strippedNumber = new StringBuilder(number);
2298 maybeStripExtension(strippedNumber);
2299 return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2303 * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2304 * for failure, this method returns a boolean value.
2305 * @param number the number that needs to be checked
2306 * @return true if the number is possible
2308 public boolean isPossibleNumber(PhoneNumber number) {
2309 return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
2313 * Helper method to check a number against a particular pattern and determine whether it matches,
2314 * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
2315 * and 10 are possible, and a number in between these possible lengths is entered, such as of
2316 * length 8, this will return TOO_LONG.
2318 private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
2319 Matcher numberMatcher = numberPattern.matcher(number);
2320 if (numberMatcher.matches()) {
2321 return ValidationResult.IS_POSSIBLE;
2323 if (numberMatcher.lookingAt()) {
2324 return ValidationResult.TOO_LONG;
2326 return ValidationResult.TOO_SHORT;
2331 * Helper method to check whether a number is too short to be a regular length phone number in a
2334 private boolean isShorterThanPossibleNormalNumber(PhoneMetadata regionMetadata, String number) {
2335 Pattern possibleNumberPattern = regexCache.getPatternForRegex(
2336 regionMetadata.getGeneralDesc().getPossibleNumberPattern());
2337 return testNumberLengthAgainstPattern(possibleNumberPattern, number) ==
2338 ValidationResult.TOO_SHORT;
2342 * Check whether a phone number is a possible number. It provides a more lenient check than
2343 * {@link #isValidNumber} in the following sense:
2345 * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
2346 * digits of the number.
2347 * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2348 * applies to all types of phone numbers in a region. Therefore, it is much faster than
2350 * <li> For fixed line numbers, many regions have the concept of area code, which together with
2351 * subscriber number constitute the national significant number. It is sometimes okay to dial
2352 * the subscriber number only when dialing in the same area. This function will return
2353 * true if the subscriber-number-only version is passed in. On the other hand, because
2354 * isValidNumber validates using information on both starting digits (for fixed line
2355 * numbers, that would most likely be area codes) and length (obviously includes the
2356 * length of area codes for fixed line numbers), it will return false for the
2357 * subscriber-number-only version.
2359 * @param number the number that needs to be checked
2360 * @return a ValidationResult object which indicates whether the number is possible
2362 public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2363 String nationalNumber = getNationalSignificantNumber(number);
2364 int countryCode = number.getCountryCode();
2365 // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
2366 // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
2367 // valid. This would need to be revisited if the possible number pattern ever differed between
2368 // various regions within those plans.
2369 if (!hasValidCountryCallingCode(countryCode)) {
2370 return ValidationResult.INVALID_COUNTRY_CODE;
2372 String regionCode = getRegionCodeForCountryCode(countryCode);
2373 // Metadata cannot be null because the country calling code is valid.
2374 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2375 Pattern possibleNumberPattern =
2376 regexCache.getPatternForRegex(metadata.getGeneralDesc().getPossibleNumberPattern());
2377 return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
2381 * Check whether a phone number is a possible number given a number in the form of a string, and
2382 * the region where the number could be dialed from. It provides a more lenient check than
2383 * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
2385 * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
2386 * with the resultant PhoneNumber object.
2388 * @param number the number that needs to be checked, in the form of a string
2389 * @param regionDialingFrom the region that we are expecting the number to be dialed from.
2390 * Note this is different from the region where the number belongs. For example, the number
2391 * +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2392 * dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2393 * region which uses an international dialling prefix of 00. When it is written as
2394 * 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2395 * can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
2397 * @return true if the number is possible
2399 public boolean isPossibleNumber(String number, String regionDialingFrom) {
2401 return isPossibleNumber(parse(number, regionDialingFrom));
2402 } catch (NumberParseException e) {
2408 * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2409 * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2410 * the PhoneNumber object passed in will not be modified.
2411 * @param number a PhoneNumber object which contains a number that is too long to be valid.
2412 * @return true if a valid phone number can be successfully extracted.
2414 public boolean truncateTooLongNumber(PhoneNumber number) {
2415 if (isValidNumber(number)) {
2418 PhoneNumber numberCopy = new PhoneNumber();
2419 numberCopy.mergeFrom(number);
2420 long nationalNumber = number.getNationalNumber();
2422 nationalNumber /= 10;
2423 numberCopy.setNationalNumber(nationalNumber);
2424 if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
2425 nationalNumber == 0) {
2428 } while (!isValidNumber(numberCopy));
2429 number.setNationalNumber(nationalNumber);
2434 * Gets an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
2436 * @param regionCode the region where the phone number is being entered
2437 * @return an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2438 * to format phone numbers in the specific region "as you type"
2440 public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
2441 return new AsYouTypeFormatter(regionCode);
2444 // Extracts country calling code from fullNumber, returns it and places the remaining number in
2445 // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2446 // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2448 int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2449 if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2450 // Country codes do not begin with a '0'.
2453 int potentialCountryCode;
2454 int numberLength = fullNumber.length();
2455 for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
2456 potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2457 if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
2458 nationalNumber.append(fullNumber.substring(i));
2459 return potentialCountryCode;
2466 * Tries to extract a country calling code from a number. This method will return zero if no
2467 * country calling code is considered to be present. Country calling codes are extracted in the
2470 * <li> by stripping the international dialing prefix of the region the person is dialing from,
2471 * if this is present in the number, and looking at the next digits
2472 * <li> by stripping the '+' sign if present and then looking at the next digits
2473 * <li> by comparing the start of the number and the country calling code of the default region.
2474 * If the number is not considered possible for the numbering plan of the default region
2475 * initially, but starts with the country calling code of this region, validation will be
2476 * reattempted after stripping this country calling code. If this number is considered a
2477 * possible number, then the first digits will be considered the country calling code and
2480 * It will throw a NumberParseException if the number starts with a '+' but the country calling
2481 * code supplied after this does not match that of any known region.
2483 * @param number non-normalized telephone number that we wish to extract a country calling
2484 * code from - may begin with '+'
2485 * @param defaultRegionMetadata metadata about the region this number may be from
2486 * @param nationalNumber a string buffer to store the national significant number in, in the case
2487 * that a country calling code was extracted. The number is appended to any existing contents.
2488 * If no country calling code was extracted, this will be left unchanged.
2489 * @param keepRawInput true if the country_code_source and preferred_carrier_code fields of
2490 * phoneNumber should be populated.
2491 * @param phoneNumber the PhoneNumber object where the country_code and country_code_source need
2492 * to be populated. Note the country_code is always populated, whereas country_code_source is
2493 * only populated when keepCountryCodeSource is true.
2494 * @return the country calling code extracted or 0 if none could be extracted
2496 // @VisibleForTesting
2497 int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
2498 StringBuilder nationalNumber, boolean keepRawInput,
2499 PhoneNumber phoneNumber)
2500 throws NumberParseException {
2501 if (number.length() == 0) {
2504 StringBuilder fullNumber = new StringBuilder(number);
2505 // Set the default prefix to be something that will never match.
2506 String possibleCountryIddPrefix = "NonMatch";
2507 if (defaultRegionMetadata != null) {
2508 possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
2511 CountryCodeSource countryCodeSource =
2512 maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
2514 phoneNumber.setCountryCodeSource(countryCodeSource);
2516 if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2517 if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
2518 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2519 "Phone number had an IDD, but after this was not "
2520 + "long enough to be a viable phone number.");
2522 int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
2523 if (potentialCountryCode != 0) {
2524 phoneNumber.setCountryCode(potentialCountryCode);
2525 return potentialCountryCode;
2528 // If this fails, they must be using a strange country calling code that we don't recognize,
2529 // or that doesn't exist.
2530 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2531 "Country calling code supplied was not recognised.");
2532 } else if (defaultRegionMetadata != null) {
2533 // Check to see if the number starts with the country calling code for the default region. If
2534 // so, we remove the country calling code, and do some checks on the validity of the number
2535 // before and after.
2536 int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2537 String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2538 String normalizedNumber = fullNumber.toString();
2539 if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2540 StringBuilder potentialNationalNumber =
2541 new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
2542 PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2543 Pattern validNumberPattern =
2544 regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
2545 maybeStripNationalPrefixAndCarrierCode(
2546 potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2547 Pattern possibleNumberPattern =
2548 regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
2549 // If the number was not valid before but is valid now, or if it was too long before, we
2550 // consider the number with the country calling code stripped to be a better result and
2551 // keep that instead.
2552 if ((!validNumberPattern.matcher(fullNumber).matches() &&
2553 validNumberPattern.matcher(potentialNationalNumber).matches()) ||
2554 testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
2555 == ValidationResult.TOO_LONG) {
2556 nationalNumber.append(potentialNationalNumber);
2558 phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
2560 phoneNumber.setCountryCode(defaultCountryCode);
2561 return defaultCountryCode;
2565 // No country calling code present.
2566 phoneNumber.setCountryCode(0);
2571 * Strips the IDD from the start of the number if present. Helper function used by
2572 * maybeStripInternationalPrefixAndNormalize.
2574 private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
2575 Matcher m = iddPattern.matcher(number);
2576 if (m.lookingAt()) {
2577 int matchEnd = m.end();
2578 // Only strip this if the first digit after the match is not a 0, since country calling codes
2579 // cannot begin with 0.
2580 Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
2581 if (digitMatcher.find()) {
2582 String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
2583 if (normalizedGroup.equals("0")) {
2587 number.delete(0, matchEnd);
2594 * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2595 * the resulting number, and indicates if an international prefix was present.
2597 * @param number the non-normalized telephone number that we wish to strip any international
2598 * dialing prefix from.
2599 * @param possibleIddPrefix the international direct dialing prefix from the region we
2600 * think this number may be dialed in
2601 * @return the corresponding CountryCodeSource if an international dialing prefix could be
2602 * removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2603 * not seem to be in international format.
2605 // @VisibleForTesting
2606 CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2607 StringBuilder number,
2608 String possibleIddPrefix) {
2609 if (number.length() == 0) {
2610 return CountryCodeSource.FROM_DEFAULT_COUNTRY;
2612 // Check to see if the number begins with one or more plus signs.
2613 Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2614 if (m.lookingAt()) {
2615 number.delete(0, m.end());
2616 // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
2618 return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
2620 // Attempt to parse the first digits as an international prefix.
2621 Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
2623 return parsePrefixAsIdd(iddPattern, number)
2624 ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2625 : CountryCodeSource.FROM_DEFAULT_COUNTRY;
2629 * Strips any national prefix (such as 0, 1) present in the number provided.
2631 * @param number the normalized telephone number that we wish to strip any national
2632 * dialing prefix from
2633 * @param metadata the metadata for the region that we think this number is from
2634 * @param carrierCode a place to insert the carrier code if one is extracted
2635 * @return true if a national prefix or carrier code (or both) could be extracted.
2637 // @VisibleForTesting
2638 boolean maybeStripNationalPrefixAndCarrierCode(
2639 StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
2640 int numberLength = number.length();
2641 String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
2642 if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
2643 // Early return for numbers of zero length.
2646 // Attempt to parse the first digits as a national prefix.
2647 Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
2648 if (prefixMatcher.lookingAt()) {
2649 Pattern nationalNumberRule =
2650 regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
2651 // Check if the original number is viable.
2652 boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
2653 // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
2654 // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
2655 // remove the national prefix.
2656 int numOfGroups = prefixMatcher.groupCount();
2657 String transformRule = metadata.getNationalPrefixTransformRule();
2658 if (transformRule == null || transformRule.length() == 0 ||
2659 prefixMatcher.group(numOfGroups) == null) {
2660 // If the original number was viable, and the resultant number is not, we return.
2661 if (isViableOriginalNumber &&
2662 !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
2665 if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
2666 carrierCode.append(prefixMatcher.group(1));
2668 number.delete(0, prefixMatcher.end());
2671 // Check that the resultant number is still viable. If not, return. Check this by copying
2672 // the string buffer and making the transformation on the copy first.
2673 StringBuilder transformedNumber = new StringBuilder(number);
2674 transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
2675 if (isViableOriginalNumber &&
2676 !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
2679 if (carrierCode != null && numOfGroups > 1) {
2680 carrierCode.append(prefixMatcher.group(1));
2682 number.replace(0, number.length(), transformedNumber.toString());
2690 * Strips any extension (as in, the part of the number dialled after the call is connected,
2691 * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
2693 * @param number the non-normalized telephone number that we wish to strip the extension from
2694 * @return the phone extension
2696 // @VisibleForTesting
2697 String maybeStripExtension(StringBuilder number) {
2698 Matcher m = EXTN_PATTERN.matcher(number);
2699 // If we find a potential extension, and the number preceding this is a viable number, we assume
2700 // it is an extension.
2701 if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
2702 // The numbers are captured into groups in the regular expression.
2703 for (int i = 1, length = m.groupCount(); i <= length; i++) {
2704 if (m.group(i) != null) {
2705 // We go through the capturing groups until we find one that captured some digits. If none
2706 // did, then we will return the empty string.
2707 String extension = m.group(i);
2708 number.delete(m.start(), number.length());
2717 * Checks to see that the region code used is valid, or if it is not valid, that the number to
2718 * parse starts with a + symbol so that we can attempt to infer the region from the number.
2719 * Returns false if it cannot use the region provided and the region cannot be inferred.
2721 private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
2722 if (!isValidRegionCode(defaultRegion)) {
2723 // If the number is null or empty, we can't infer the region.
2724 if ((numberToParse == null) || (numberToParse.length() == 0) ||
2725 !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
2733 * Parses a string and returns it in proto buffer format. This method will throw a
2734 * {@link com.google.i18n.phonenumbers.NumberParseException} if the number is not considered to be
2735 * a possible number. Note that validation of whether the number is actually a valid number for a
2736 * particular region is not performed. This can be done separately with {@link #isValidNumber}.
2738 * @param numberToParse number that we are attempting to parse. This can contain formatting
2739 * such as +, ( and -, as well as a phone number extension. It can also
2740 * be provided in RFC3966 format.
2741 * @param defaultRegion region that we are expecting the number to be from. This is only used
2742 * if the number being parsed is not written in international format.
2743 * The country_code for the number in this case would be stored as that
2744 * of the default region supplied. If the number is guaranteed to
2745 * start with a '+' followed by the country calling code, then
2746 * "ZZ" or null can be supplied.
2747 * @return a phone number proto buffer filled with the parsed number
2748 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2749 * no default region was supplied and the number is not in
2750 * international format (does not start with +)
2752 public PhoneNumber parse(String numberToParse, String defaultRegion)
2753 throws NumberParseException {
2754 PhoneNumber phoneNumber = new PhoneNumber();
2755 parse(numberToParse, defaultRegion, phoneNumber);
2760 * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
2761 * decrease object creation when invoked many times.
2763 public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
2764 throws NumberParseException {
2765 parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
2769 * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
2770 * in that it always populates the raw_input field of the protocol buffer with numberToParse as
2771 * well as the country_code_source field.
2773 * @param numberToParse number that we are attempting to parse. This can contain formatting
2774 * such as +, ( and -, as well as a phone number extension.
2775 * @param defaultRegion region that we are expecting the number to be from. This is only used
2776 * if the number being parsed is not written in international format.
2777 * The country calling code for the number in this case would be stored
2778 * as that of the default region supplied.
2779 * @return a phone number proto buffer filled with the parsed number
2780 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2781 * no default region was supplied
2783 public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
2784 throws NumberParseException {
2785 PhoneNumber phoneNumber = new PhoneNumber();
2786 parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
2791 * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
2792 * a parameter to decrease object creation when invoked many times.
2794 public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
2795 PhoneNumber phoneNumber)
2796 throws NumberParseException {
2797 parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
2801 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
2802 * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
2803 * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
2805 * @param text the text to search for phone numbers, null for no text
2806 * @param defaultRegion region that we are expecting the number to be from. This is only used
2807 * if the number being parsed is not written in international format. The
2808 * country_code for the number in this case would be stored as that of
2809 * the default region supplied. May be null if only international
2810 * numbers are expected.
2812 public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
2813 return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
2817 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
2819 * @param text the text to search for phone numbers, null for no text
2820 * @param defaultRegion region that we are expecting the number to be from. This is only used
2821 * if the number being parsed is not written in international format. The
2822 * country_code for the number in this case would be stored as that of
2823 * the default region supplied. May be null if only international
2824 * numbers are expected.
2825 * @param leniency the leniency to use when evaluating candidate phone numbers
2826 * @param maxTries the maximum number of invalid numbers to try before giving up on the
2827 * text. This is to cover degenerate cases where the text has a lot of
2828 * false positives in it. Must be {@code >= 0}.
2830 public Iterable<PhoneNumberMatch> findNumbers(
2831 final CharSequence text, final String defaultRegion, final Leniency leniency,
2832 final long maxTries) {
2834 return new Iterable<PhoneNumberMatch>() {
2836 public Iterator<PhoneNumberMatch> iterator() {
2837 return new PhoneNumberMatcher(
2838 PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
2844 * A helper function to set the values related to leading zeros in a PhoneNumber.
2846 static void setItalianLeadingZerosForPhoneNumber(String nationalNumber, PhoneNumber phoneNumber) {
2847 if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') {
2848 phoneNumber.setItalianLeadingZero(true);
2849 int numberOfLeadingZeros = 1;
2850 // Note that if the national number is all "0"s, the last "0" is not counted as a leading
2852 while (numberOfLeadingZeros < nationalNumber.length() - 1 &&
2853 nationalNumber.charAt(numberOfLeadingZeros) == '0') {
2854 numberOfLeadingZeros++;
2856 if (numberOfLeadingZeros != 1) {
2857 phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros);
2863 * Parses a string and fills up the phoneNumber. This method is the same as the public
2864 * parse() method, with the exception that it allows the default region to be null, for use by
2865 * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
2866 * to be null or unknown ("ZZ").
2868 private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
2869 boolean checkRegion, PhoneNumber phoneNumber)
2870 throws NumberParseException {
2871 if (numberToParse == null) {
2872 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2873 "The phone number supplied was null.");
2874 } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
2875 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2876 "The string supplied was too long to parse.");
2879 StringBuilder nationalNumber = new StringBuilder();
2880 buildNationalNumberForParsing(numberToParse, nationalNumber);
2882 if (!isViablePhoneNumber(nationalNumber.toString())) {
2883 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2884 "The string supplied did not seem to be a phone number.");
2887 // Check the region supplied is valid, or that the extracted number starts with some sort of +
2888 // sign so the number's region can be determined.
2889 if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
2890 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2891 "Missing or invalid default region.");
2895 phoneNumber.setRawInput(numberToParse);
2897 // Attempt to parse extension first, since it doesn't require region-specific data and we want
2898 // to have the non-normalised number here.
2899 String extension = maybeStripExtension(nationalNumber);
2900 if (extension.length() > 0) {
2901 phoneNumber.setExtension(extension);
2904 PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
2905 // Check to see if the number is given in international format so we know whether this number is
2906 // from the default region or not.
2907 StringBuilder normalizedNationalNumber = new StringBuilder();
2908 int countryCode = 0;
2910 // TODO: This method should really just take in the string buffer that has already
2911 // been created, and just remove the prefix, rather than taking in a string and then
2912 // outputting a string buffer.
2913 countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
2914 normalizedNationalNumber, keepRawInput, phoneNumber);
2915 } catch (NumberParseException e) {
2916 Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
2917 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
2918 matcher.lookingAt()) {
2919 // Strip the plus-char, and try again.
2920 countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
2921 regionMetadata, normalizedNationalNumber,
2922 keepRawInput, phoneNumber);
2923 if (countryCode == 0) {
2924 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2925 "Could not interpret numbers after plus-sign.");
2928 throw new NumberParseException(e.getErrorType(), e.getMessage());
2931 if (countryCode != 0) {
2932 String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
2933 if (!phoneNumberRegion.equals(defaultRegion)) {
2934 // Metadata cannot be null because the country calling code is valid.
2935 regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
2938 // If no extracted country calling code, use the region supplied instead. The national number
2939 // is just the normalized version of the number we were given to parse.
2940 normalize(nationalNumber);
2941 normalizedNationalNumber.append(nationalNumber);
2942 if (defaultRegion != null) {
2943 countryCode = regionMetadata.getCountryCode();
2944 phoneNumber.setCountryCode(countryCode);
2945 } else if (keepRawInput) {
2946 phoneNumber.clearCountryCodeSource();
2949 if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
2950 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2951 "The string supplied is too short to be a phone number.");
2953 if (regionMetadata != null) {
2954 StringBuilder carrierCode = new StringBuilder();
2955 StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
2956 maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
2957 // We require that the NSN remaining after stripping the national prefix and carrier code be
2958 // of a possible length for the region. Otherwise, we don't do the stripping, since the
2959 // original number could be a valid short number.
2960 if (!isShorterThanPossibleNormalNumber(regionMetadata, potentialNationalNumber.toString())) {
2961 normalizedNationalNumber = potentialNationalNumber;
2963 phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
2967 int lengthOfNationalNumber = normalizedNationalNumber.length();
2968 if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
2969 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2970 "The string supplied is too short to be a phone number.");
2972 if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
2973 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2974 "The string supplied is too long to be a phone number.");
2976 setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber.toString(), phoneNumber);
2977 phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
2981 * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
2982 * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
2984 private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
2985 int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
2986 if (indexOfPhoneContext > 0) {
2987 int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
2988 // If the phone context contains a phone number prefix, we need to capture it, whereas domains
2990 if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
2991 // Additional parameters might follow the phone context. If so, we will remove them here
2992 // because the parameters after phone context are not important for parsing the
2994 int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
2995 if (phoneContextEnd > 0) {
2996 nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
2998 nationalNumber.append(numberToParse.substring(phoneContextStart));
3002 // Now append everything between the "tel:" prefix and the phone-context. This should include
3003 // the national number, an optional extension or isdn-subaddress component. Note we also
3004 // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
3005 // In that case, we append everything from the beginning.
3006 int indexOfRfc3966Prefix = numberToParse.indexOf(RFC3966_PREFIX);
3007 int indexOfNationalNumber = (indexOfRfc3966Prefix >= 0) ?
3008 indexOfRfc3966Prefix + RFC3966_PREFIX.length() : 0;
3009 nationalNumber.append(numberToParse.substring(indexOfNationalNumber, indexOfPhoneContext));
3011 // Extract a possible number from the string passed in (this strips leading characters that
3012 // could not be the start of a phone number.)
3013 nationalNumber.append(extractPossibleNumber(numberToParse));
3016 // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
3017 // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
3018 int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
3019 if (indexOfIsdn > 0) {
3020 nationalNumber.delete(indexOfIsdn, nationalNumber.length());
3022 // If both phone context and isdn-subaddress are absent but other parameters are present, the
3023 // parameters are left in nationalNumber. This is because we are concerned about deleting
3024 // content from a potential number string when there is no strong evidence that the number is
3025 // actually written in RFC3966.
3029 * Takes two phone numbers and compares them for equality.
3031 * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
3032 * and any extension present are the same.
3033 * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
3035 * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
3036 * the same, and one NSN could be a shorter version of the other number. This includes the case
3037 * where one has an extension specified, and the other does not.
3038 * Returns NO_MATCH otherwise.
3039 * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
3040 * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
3042 * @param firstNumberIn first number to compare
3043 * @param secondNumberIn second number to compare
3045 * @return NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
3046 * of the two numbers, described in the method definition.
3048 public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
3049 // Make copies of the phone number so that the numbers passed in are not edited.
3050 PhoneNumber firstNumber = new PhoneNumber();
3051 firstNumber.mergeFrom(firstNumberIn);
3052 PhoneNumber secondNumber = new PhoneNumber();
3053 secondNumber.mergeFrom(secondNumberIn);
3054 // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
3055 // empty-string extensions so that we can use the proto-buffer equality method.
3056 firstNumber.clearRawInput();
3057 firstNumber.clearCountryCodeSource();
3058 firstNumber.clearPreferredDomesticCarrierCode();
3059 secondNumber.clearRawInput();
3060 secondNumber.clearCountryCodeSource();
3061 secondNumber.clearPreferredDomesticCarrierCode();
3062 if (firstNumber.hasExtension() &&
3063 firstNumber.getExtension().length() == 0) {
3064 firstNumber.clearExtension();
3066 if (secondNumber.hasExtension() &&
3067 secondNumber.getExtension().length() == 0) {
3068 secondNumber.clearExtension();
3070 // Early exit if both had extensions and these are different.
3071 if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
3072 !firstNumber.getExtension().equals(secondNumber.getExtension())) {
3073 return MatchType.NO_MATCH;
3075 int firstNumberCountryCode = firstNumber.getCountryCode();
3076 int secondNumberCountryCode = secondNumber.getCountryCode();
3077 // Both had country_code specified.
3078 if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
3079 if (firstNumber.exactlySameAs(secondNumber)) {
3080 return MatchType.EXACT_MATCH;
3081 } else if (firstNumberCountryCode == secondNumberCountryCode &&
3082 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3083 // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3084 // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3085 // shorter variant of the other.
3086 return MatchType.SHORT_NSN_MATCH;
3088 // This is not a match.
3089 return MatchType.NO_MATCH;
3091 // Checks cases where one or both country_code fields were not specified. To make equality
3092 // checks easier, we first set the country_code fields to be equal.
3093 firstNumber.setCountryCode(secondNumberCountryCode);
3094 // If all else was the same, then this is an NSN_MATCH.
3095 if (firstNumber.exactlySameAs(secondNumber)) {
3096 return MatchType.NSN_MATCH;
3098 if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3099 return MatchType.SHORT_NSN_MATCH;
3101 return MatchType.NO_MATCH;
3104 // Returns true when one national number is the suffix of the other or both are the same.
3105 private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
3106 PhoneNumber secondNumber) {
3107 String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
3108 String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
3109 // Note that endsWith returns true if the numbers are equal.
3110 return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
3111 secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
3115 * Takes two phone numbers as strings and compares them for equality. This is a convenience
3116 * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3118 * @param firstNumber first number to compare. Can contain formatting, and can have country
3119 * calling code specified with + at the start.
3120 * @param secondNumber second number to compare. Can contain formatting, and can have country
3121 * calling code specified with + at the start.
3122 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3123 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3125 public MatchType isNumberMatch(String firstNumber, String secondNumber) {
3127 PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
3128 return isNumberMatch(firstNumberAsProto, secondNumber);
3129 } catch (NumberParseException e) {
3130 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3132 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3133 return isNumberMatch(secondNumberAsProto, firstNumber);
3134 } catch (NumberParseException e2) {
3135 if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3137 PhoneNumber firstNumberProto = new PhoneNumber();
3138 PhoneNumber secondNumberProto = new PhoneNumber();
3139 parseHelper(firstNumber, null, false, false, firstNumberProto);
3140 parseHelper(secondNumber, null, false, false, secondNumberProto);
3141 return isNumberMatch(firstNumberProto, secondNumberProto);
3142 } catch (NumberParseException e3) {
3143 // Fall through and return MatchType.NOT_A_NUMBER.
3149 // One or more of the phone numbers we are trying to match is not a viable phone number.
3150 return MatchType.NOT_A_NUMBER;
3154 * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
3155 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3157 * @param firstNumber first number to compare in proto buffer format.
3158 * @param secondNumber second number to compare. Can contain formatting, and can have country
3159 * calling code specified with + at the start.
3160 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3161 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3163 public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
3164 // First see if the second number has an implicit country calling code, by attempting to parse
3167 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3168 return isNumberMatch(firstNumber, secondNumberAsProto);
3169 } catch (NumberParseException e) {
3170 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3171 // The second number has no country calling code. EXACT_MATCH is no longer possible.
3172 // We parse it as if the region was the same as that for the first number, and if
3173 // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3174 String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
3176 if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
3177 PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
3178 MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
3179 if (match == MatchType.EXACT_MATCH) {
3180 return MatchType.NSN_MATCH;
3184 // If the first number didn't have a valid country calling code, then we parse the
3185 // second number without one as well.
3186 PhoneNumber secondNumberProto = new PhoneNumber();
3187 parseHelper(secondNumber, null, false, false, secondNumberProto);
3188 return isNumberMatch(firstNumber, secondNumberProto);
3190 } catch (NumberParseException e2) {
3191 // Fall-through to return NOT_A_NUMBER.
3195 // One or more of the phone numbers we are trying to match is not a viable phone number.
3196 return MatchType.NOT_A_NUMBER;
3200 * Returns true if the number can be dialled from outside the region, or unknown. If the number
3201 * can only be dialled from within the region, returns false. Does not check the number is a valid
3202 * number. Note that, at the moment, this method does not handle short numbers.
3203 * TODO: Make this method public when we have enough metadata to make it worthwhile.
3205 * @param number the phone-number for which we want to know whether it is diallable from
3206 * outside the region
3208 // @VisibleForTesting
3209 boolean canBeInternationallyDialled(PhoneNumber number) {
3210 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3211 if (metadata == null) {
3212 // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3213 // internationally diallable, and will be caught here.
3216 String nationalSignificantNumber = getNationalSignificantNumber(number);
3217 return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
3221 * Returns true if the supplied region supports mobile number portability. Returns false for
3222 * invalid, unknown or regions that don't support mobile number portability.
3224 * @param regionCode the region for which we want to know whether it supports mobile number
3225 * portability or not.
3227 public boolean isMobileNumberPortableRegion(String regionCode) {
3228 PhoneMetadata metadata = getMetadataForRegion(regionCode);
3229 if (metadata == null) {
3230 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
3233 return metadata.isMobileNumberPortableRegion();