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() {
61 public InputStream loadMetadata(String metadataFileName) {
62 return PhoneNumberUtil.class.getResourceAsStream(metadataFileName);
66 private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName());
68 /** Flags to use when compiling regular expressions for phone numbers. */
69 static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
70 // The minimum and maximum length of the national significant number.
71 private static final int MIN_LENGTH_FOR_NSN = 2;
72 // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
73 static final int MAX_LENGTH_FOR_NSN = 17;
74 // The maximum length of the country calling code.
75 static final int MAX_LENGTH_COUNTRY_CODE = 3;
76 // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
77 // input from overflowing the regular-expression engine.
78 private static final int MAX_INPUT_STRING_LENGTH = 250;
80 private static final String META_DATA_FILE_PREFIX =
81 "/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto";
83 // Region-code for the unknown region.
84 private static final String UNKNOWN_REGION = "ZZ";
86 private static final int NANPA_COUNTRY_CODE = 1;
88 // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
89 // a mobile phone in Colombia.
90 private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
92 // Map of country calling codes that use a mobile token before the area code. One example of when
93 // this is relevant is when determining the length of the national destination code, which should
94 // be the length of the area code plus the length of the mobile token.
95 private static final Map<Integer, String> MOBILE_TOKEN_MAPPINGS;
97 // The PLUS_SIGN signifies the international prefix.
98 static final char PLUS_SIGN = '+';
100 private static final char STAR_SIGN = '*';
102 private static final String RFC3966_EXTN_PREFIX = ";ext=";
103 private static final String RFC3966_PREFIX = "tel:";
104 private static final String RFC3966_PHONE_CONTEXT = ";phone-context=";
105 private static final String RFC3966_ISDN_SUBADDRESS = ";isub=";
107 // A map that contains characters that are essential when dialling. That means any of the
108 // characters in this map must not be removed from a number when dialling, otherwise the call
109 // will not reach the intended destination.
110 private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
112 // Only upper-case variants of alpha characters are stored.
113 private static final Map<Character, Character> ALPHA_MAPPINGS;
115 // For performance reasons, amalgamate both into one map.
116 private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
118 // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
119 // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
120 private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
123 HashMap<Integer, String> mobileTokenMap = new HashMap<Integer, String>();
124 mobileTokenMap.put(52, "1");
125 mobileTokenMap.put(54, "9");
126 MOBILE_TOKEN_MAPPINGS = Collections.unmodifiableMap(mobileTokenMap);
128 // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
129 // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
130 HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
131 asciiDigitMappings.put('0', '0');
132 asciiDigitMappings.put('1', '1');
133 asciiDigitMappings.put('2', '2');
134 asciiDigitMappings.put('3', '3');
135 asciiDigitMappings.put('4', '4');
136 asciiDigitMappings.put('5', '5');
137 asciiDigitMappings.put('6', '6');
138 asciiDigitMappings.put('7', '7');
139 asciiDigitMappings.put('8', '8');
140 asciiDigitMappings.put('9', '9');
142 HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
143 alphaMap.put('A', '2');
144 alphaMap.put('B', '2');
145 alphaMap.put('C', '2');
146 alphaMap.put('D', '3');
147 alphaMap.put('E', '3');
148 alphaMap.put('F', '3');
149 alphaMap.put('G', '4');
150 alphaMap.put('H', '4');
151 alphaMap.put('I', '4');
152 alphaMap.put('J', '5');
153 alphaMap.put('K', '5');
154 alphaMap.put('L', '5');
155 alphaMap.put('M', '6');
156 alphaMap.put('N', '6');
157 alphaMap.put('O', '6');
158 alphaMap.put('P', '7');
159 alphaMap.put('Q', '7');
160 alphaMap.put('R', '7');
161 alphaMap.put('S', '7');
162 alphaMap.put('T', '8');
163 alphaMap.put('U', '8');
164 alphaMap.put('V', '8');
165 alphaMap.put('W', '9');
166 alphaMap.put('X', '9');
167 alphaMap.put('Y', '9');
168 alphaMap.put('Z', '9');
169 ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
171 HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
172 combinedMap.putAll(ALPHA_MAPPINGS);
173 combinedMap.putAll(asciiDigitMappings);
174 ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
176 HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
177 diallableCharMap.putAll(asciiDigitMappings);
178 diallableCharMap.put(PLUS_SIGN, PLUS_SIGN);
179 diallableCharMap.put('*', '*');
180 DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
182 HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
183 // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
184 for (char c : ALPHA_MAPPINGS.keySet()) {
185 allPlusNumberGroupings.put(Character.toLowerCase(c), c);
186 allPlusNumberGroupings.put(c, c);
188 allPlusNumberGroupings.putAll(asciiDigitMappings);
189 // Put grouping symbols.
190 allPlusNumberGroupings.put('-', '-');
191 allPlusNumberGroupings.put('\uFF0D', '-');
192 allPlusNumberGroupings.put('\u2010', '-');
193 allPlusNumberGroupings.put('\u2011', '-');
194 allPlusNumberGroupings.put('\u2012', '-');
195 allPlusNumberGroupings.put('\u2013', '-');
196 allPlusNumberGroupings.put('\u2014', '-');
197 allPlusNumberGroupings.put('\u2015', '-');
198 allPlusNumberGroupings.put('\u2212', '-');
199 allPlusNumberGroupings.put('/', '/');
200 allPlusNumberGroupings.put('\uFF0F', '/');
201 allPlusNumberGroupings.put(' ', ' ');
202 allPlusNumberGroupings.put('\u3000', ' ');
203 allPlusNumberGroupings.put('\u2060', ' ');
204 allPlusNumberGroupings.put('.', '.');
205 allPlusNumberGroupings.put('\uFF0E', '.');
206 ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
209 // Pattern that makes it easy to distinguish whether a region has a unique international dialing
210 // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
211 // represented as a string that contains a sequence of ASCII digits. If there are multiple
212 // available international prefixes in a region, they will be represented as a regex string that
213 // always contains character(s) other than ASCII digits.
214 // Note this regex also includes tilde, which signals waiting for the tone.
215 private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
216 Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
218 // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
219 // found as a leading character only.
220 // This consists of dash characters, white space characters, full stops, slashes,
221 // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
222 // placeholder for carrier information in some phone numbers. Full-width variants are also
224 static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
225 "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
227 private static final String DIGITS = "\\p{Nd}";
228 // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
229 private static final String VALID_ALPHA =
230 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
231 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
232 static final String PLUS_CHARS = "+\uFF0B";
233 static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
234 private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
235 private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
237 // Regular expression of acceptable characters that may start a phone number for the purposes of
238 // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
239 // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
240 // does not contain alpha characters, although they may be used later in the number. It also does
241 // not include other punctuation, as this will be stripped later during parsing and is of no
242 // information value when parsing a number.
243 private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
244 private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
246 // Regular expression of characters typically used to start a second phone number for the purposes
247 // of parsing. This allows us to strip off parts of the number that are actually the start of
248 // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
249 // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
250 // extension so that the first number is parsed correctly.
251 private static final String SECOND_NUMBER_START = "[\\\\/] *x";
252 static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
254 // Regular expression of trailing characters that we want to remove. We remove all characters that
255 // are not alpha or numerical characters. The hash character is retained here, as it may signify
256 // the previous block was an extension.
257 private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
258 static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
260 // We use this pattern to check if the phone number has at least three letters in it - if so, then
261 // we treat it as a number where some phone-number digits are represented by letters.
262 private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
264 // Regular expression of viable phone numbers. This is location independent. Checks we have at
265 // least three leading digits, and only valid punctuation, alpha characters and
266 // digits in the phone number. Does not include extension data.
267 // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
268 // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
270 // Corresponds to the following:
271 // [digits]{minLengthNsn}|
272 // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
274 // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
275 // as "15" etc, but only if there is no punctuation in them. The second expression restricts the
276 // number of digits to three or more, but then allows them to be in international form, and to
277 // have alpha-characters and punctuation.
279 // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
280 private static final String VALID_PHONE_NUMBER =
281 DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" +
282 "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
283 VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
285 // Default extension prefix to use when formatting. This will be put in front of any extension
286 // component of the number, after the main national number is formatted. For example, if you wish
287 // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
288 // as the default extension prefix. This can be overridden by region-specific preferences.
289 private static final String DEFAULT_EXTN_PREFIX = " ext. ";
291 // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
293 private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
294 // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
295 // case-insensitive regexp match. Wide character versions are also provided after each ASCII
297 private static final String EXTN_PATTERNS_FOR_PARSING;
298 static final String EXTN_PATTERNS_FOR_MATCHING;
300 // One-character symbols that can be used to indicate an extension.
301 String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
302 // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
303 // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
305 String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
307 EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
308 EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
312 * Helper initialiser method to create the regular-expression pattern to match extensions,
313 * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
315 private static String createExtnPattern(String singleExtnSymbols) {
316 // There are three regular expressions here. The first covers RFC 3966 format, where the
317 // extension is added using ";ext=". The second more generic one starts with optional white
318 // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
319 // the numbers themselves. The other one covers the special case of American numbers where the
320 // extension is written with a hash at the end, such as "- 503#".
321 // Note that the only capturing groups should be around the digits that you want to capture as
322 // part of the extension, or else parsing will fail!
323 // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
324 // for representing the accented o - the character itself, and one in the unicode decomposed
325 // form with the combining acute accent.
326 return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
327 "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
328 "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
329 "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
330 "[- ]+(" + DIGITS + "{1,5})#");
333 // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
334 // digits, for use when parsing.
335 private static final Pattern EXTN_PATTERN =
336 Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
338 // We append optionally the extension pattern to the end here, as a valid phone number may
339 // have an extension prefix appended, followed by 1 or more digits.
340 private static final Pattern VALID_PHONE_NUMBER_PATTERN =
341 Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
343 static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
345 // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
346 // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
347 // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
349 private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
350 private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
351 private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
352 private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
354 // A pattern that is used to determine if the national prefix formatting rule has the first group
355 // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
356 // for unbalanced parentheses.
357 private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?");
359 private static PhoneNumberUtil instance = null;
361 public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
364 * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
365 * E123. For example, the number of the Google Switzerland office will be written as
366 * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
367 * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
368 * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
369 * separating symbols replaced with a hyphen, and with any phone number extension appended with
370 * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
372 * Note: If you are considering storing the number in a neutral format, you are highly advised to
373 * use the PhoneNumber class.
375 public enum PhoneNumberFormat {
383 * Type of phone numbers.
385 public enum PhoneNumberType {
388 // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
389 // mobile numbers by looking at the phone number itself.
390 FIXED_LINE_OR_MOBILE,
394 // The cost of this call is shared between the caller and the recipient, and is hence typically
395 // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
398 // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
400 // A personal number is associated with a particular person, and may be routed to either a
401 // MOBILE or FIXED_LINE number. Some more information can be found here:
402 // http://en.wikipedia.org/wiki/Personal_Numbers
405 // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
406 // specific offices, but allow one number to be used for a company.
408 // Used for "Voice Mail Access Numbers".
410 // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
416 * Types of phone number matches. See detailed description beside the isNumberMatch() method.
418 public enum MatchType {
427 * Possible outcomes when testing if a PhoneNumber is possible.
429 public enum ValidationResult {
431 INVALID_COUNTRY_CODE,
437 * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
438 * segments. The levels here are ordered in increasing strictness.
440 public enum Leniency {
442 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
443 * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
447 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
448 return util.isPossibleNumber(number);
452 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
453 * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
454 * in national format must have their national-prefix present if it is usually written for a
455 * number of this type.
459 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
460 if (!util.isValidNumber(number) ||
461 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) {
464 return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util);
468 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
469 * are grouped in a possible way for this locale. For example, a US number written as
470 * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
471 * "650 253 0000", "650 2530000" or "6502530000" are.
472 * Numbers with more than one '/' symbol in the national significant number are also dropped at
475 * Warning: This level might result in lower coverage especially for regions outside of country
476 * code "+1". If you are not sure about which level to use, email the discussion group
477 * libphonenumber-discuss@googlegroups.com.
481 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
482 if (!util.isValidNumber(number) ||
483 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
484 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
485 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
488 return PhoneNumberMatcher.checkNumberGroupingIsValid(
489 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
490 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
491 StringBuilder normalizedCandidate,
492 String[] expectedNumberGroups) {
493 return PhoneNumberMatcher.allNumberGroupsRemainGrouped(
494 util, number, normalizedCandidate, expectedNumberGroups);
500 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
501 * are grouped in the same way that we would have formatted it, or as a single block. For
502 * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
503 * "650 253 0000" or "6502530000" are.
504 * Numbers with more than one '/' symbol are also dropped at this level.
506 * Warning: This level might result in lower coverage especially for regions outside of country
507 * code "+1". If you are not sure about which level to use, email the discussion group
508 * libphonenumber-discuss@googlegroups.com.
512 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
513 if (!util.isValidNumber(number) ||
514 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
515 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
516 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
519 return PhoneNumberMatcher.checkNumberGroupingIsValid(
520 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
521 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
522 StringBuilder normalizedCandidate,
523 String[] expectedNumberGroups) {
524 return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent(
525 util, number, normalizedCandidate, expectedNumberGroups);
531 /** Returns true if {@code number} is a verified number according to this leniency. */
532 abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
535 // A mapping from a country calling code to the region codes which denote the region represented
536 // by that country calling code. In the case of multiple regions sharing a calling code, such as
537 // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
539 private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap;
541 // The set of regions that share country calling code 1.
542 // There are roughly 26 regions.
543 // We set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
544 private final Set<String> nanpaRegions = new HashSet<String>(35);
546 // A mapping from a region code to the PhoneMetadata for that region.
547 // Note: Synchronization, though only needed for the Android version of the library, is used in
548 // all versions for consistency.
549 private final Map<String, PhoneMetadata> regionToMetadataMap =
550 Collections.synchronizedMap(new HashMap<String, PhoneMetadata>());
552 // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
553 // that country calling code. Examples of the country calling codes include 800 (International
554 // Toll Free Service) and 808 (International Shared Cost Service).
555 // Note: Synchronization, though only needed for the Android version of the library, is used in
556 // all versions for consistency.
557 private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
558 Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>());
560 // A cache for frequently used region-specific regular expressions.
561 // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on
562 // performance measurements.
563 private final RegexCache regexCache = new RegexCache(100);
565 // The set of regions the library supports.
566 // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
567 // load factor of roughly 0.75.
568 private final Set<String> supportedRegions = new HashSet<String>(320);
570 // The set of county calling codes that map to the non-geo entity region ("001"). This set
571 // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
572 private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>();
574 // The prefix of the metadata files from which region data is loaded.
575 private final String currentFilePrefix;
576 // The metadata loader used to inject alternative metadata sources.
577 private final MetadataLoader metadataLoader;
580 * This class implements a singleton, the constructor is only visible to facilitate testing.
582 // @VisibleForTesting
583 PhoneNumberUtil(String filePrefix, MetadataLoader metadataLoader,
584 Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
585 this.currentFilePrefix = filePrefix;
586 this.metadataLoader = metadataLoader;
587 this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
588 for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) {
589 List<String> regionCodes = entry.getValue();
590 // We can assume that if the county calling code maps to the non-geo entity region code then
591 // that's the only region code it maps to.
592 if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) {
593 // This is the subset of all country codes that map to the non-geo entity region code.
594 countryCodesForNonGeographicalRegion.add(entry.getKey());
596 // The supported regions set does not include the "001" non-geo entity region code.
597 supportedRegions.addAll(regionCodes);
600 // If the non-geo entity still got added to the set of supported regions it must be because
601 // there are entries that list the non-geo entity alongside normal regions (which is wrong).
602 // If we discover this, remove the non-geo entity from the set of supported regions and log.
603 if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) {
604 logger.log(Level.WARNING, "invalid metadata " +
605 "(country calling code was mapped to the non-geo entity as well as specific region(s))");
607 nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
610 // @VisibleForTesting
611 void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode,
612 MetadataLoader metadataLoader) {
613 boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
614 String fileName = filePrefix + "_" +
615 (isNonGeoRegion ? String.valueOf(countryCallingCode) : regionCode);
616 InputStream source = metadataLoader.loadMetadata(fileName);
617 if (source == null) {
618 logger.log(Level.SEVERE, "missing metadata: " + fileName);
619 throw new IllegalStateException("missing metadata: " + fileName);
621 ObjectInputStream in = null;
623 in = new ObjectInputStream(source);
624 PhoneMetadataCollection metadataCollection = loadMetadataAndCloseInput(in);
625 List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
626 if (metadataList.isEmpty()) {
627 logger.log(Level.SEVERE, "empty metadata: " + fileName);
628 throw new IllegalStateException("empty metadata: " + fileName);
630 if (metadataList.size() > 1) {
631 logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName);
633 PhoneMetadata metadata = metadataList.get(0);
634 if (isNonGeoRegion) {
635 countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);
637 regionToMetadataMap.put(regionCode, metadata);
639 } catch (IOException e) {
640 logger.log(Level.SEVERE, "cannot load/parse metadata: " + fileName, e);
641 throw new RuntimeException("cannot load/parse metadata: " + fileName, e);
646 * Loads the metadata protocol buffer from the given stream and closes the stream afterwards. Any
647 * exceptions that occur while reading the stream are propagated (though exceptions that occur
648 * when the stream is closed will be ignored).
650 * @param source the non-null stream from which metadata is to be read.
651 * @return the loaded metadata protocol buffer.
653 private static PhoneMetadataCollection loadMetadataAndCloseInput(ObjectInputStream source) {
654 PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
656 metadataCollection.readExternal(source);
657 } catch (IOException e) {
658 logger.log(Level.WARNING, "error reading input (ignored)", e);
662 } catch (IOException e) {
663 logger.log(Level.WARNING, "error closing input stream (ignored)", e);
665 return metadataCollection;
671 * Attempts to extract a possible number from the string passed in. This currently strips all
672 * leading characters that cannot be used to start a phone number. Characters that can be used to
673 * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
674 * are found in the number passed in, an empty string is returned. This function also attempts to
675 * strip off any alternative extensions or endings if two or more are present, such as in the case
676 * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
677 * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
678 * number is parsed correctly.
680 * @param number the string that might contain a phone number
681 * @return the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
682 * string if no character used to start phone numbers (such as + or any digit) is
683 * found in the number
685 static String extractPossibleNumber(String number) {
686 Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
688 number = number.substring(m.start());
689 // Remove trailing non-alpha non-numerical characters.
690 Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
691 if (trailingCharsMatcher.find()) {
692 number = number.substring(0, trailingCharsMatcher.start());
693 logger.log(Level.FINER, "Stripped trailing characters: " + number);
695 // Check for extra numbers at the end.
696 Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
697 if (secondNumber.find()) {
698 number = number.substring(0, secondNumber.start());
707 * Checks to see if the string of characters could possibly be a phone number at all. At the
708 * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
709 * commonly found in phone numbers.
710 * This method does not require the number to be normalized in advance - but does assume that
711 * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
713 * @param number string to be checked for viability as a phone number
714 * @return true if the number could be a phone number of some sort, otherwise false
716 // @VisibleForTesting
717 static boolean isViablePhoneNumber(String number) {
718 if (number.length() < MIN_LENGTH_FOR_NSN) {
721 Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
726 * Normalizes a string of characters representing a phone number. This performs the following
728 * Punctuation is stripped.
729 * For ALPHA/VANITY numbers:
730 * Letters are converted to their numeric representation on a telephone keypad. The keypad
731 * used here is the one defined in ITU Recommendation E.161. This is only done if there are
732 * 3 or more letters in the number, to lessen the risk that such letters are typos.
734 * Wide-ascii digits are converted to normal ASCII (European) digits.
735 * Arabic-Indic numerals are converted to European numerals.
736 * Spurious alpha characters are stripped.
738 * @param number a string of characters representing a phone number
739 * @return the normalized string version of the phone number
741 static String normalize(String number) {
742 Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
744 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
746 return normalizeDigitsOnly(number);
751 * Normalizes a string of characters representing a phone number. This is a wrapper for
752 * normalize(String number) but does in-place normalization of the StringBuilder provided.
754 * @param number a StringBuilder of characters representing a phone number that will be
755 * normalized in place
757 static void normalize(StringBuilder number) {
758 String normalizedNumber = normalize(number.toString());
759 number.replace(0, number.length(), normalizedNumber);
763 * Normalizes a string of characters representing a phone number. This converts wide-ascii and
764 * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
766 * @param number a string of characters representing a phone number
767 * @return the normalized string version of the phone number
769 public static String normalizeDigitsOnly(String number) {
770 return normalizeDigits(number, false /* strip non-digits */).toString();
773 static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
774 StringBuilder normalizedDigits = new StringBuilder(number.length());
775 for (char c : number.toCharArray()) {
776 int digit = Character.digit(c, 10);
778 normalizedDigits.append(digit);
779 } else if (keepNonDigits) {
780 normalizedDigits.append(c);
783 return normalizedDigits;
787 * Normalizes a string of characters representing a phone number. This strips all characters which
788 * are not diallable on a mobile phone keypad (including all non-ASCII digits).
790 * @param number a string of characters representing a phone number
791 * @return the normalized string version of the phone number
793 static String normalizeDiallableCharsOnly(String number) {
794 return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
798 * Converts all alpha characters in a number to their respective digits on a keypad, but retains
799 * existing formatting.
801 public static String convertAlphaCharactersInNumber(String number) {
802 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
806 * Gets the length of the geographical area code from the
807 * PhoneNumber object passed in, so that clients could use it
808 * to split a national significant number into geographical area code and subscriber number. It
809 * works in such a way that the resultant subscriber number should be diallable, at least on some
810 * devices. An example of how this could be used:
813 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
814 * PhoneNumber number = phoneUtil.parse("16502530000", "US");
815 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
817 * String subscriberNumber;
819 * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
820 * if (areaCodeLength > 0) {
821 * areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
822 * subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
825 * subscriberNumber = nationalSignificantNumber;
829 * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
830 * using it for most purposes, but recommends using the more general {@code national_number}
831 * instead. Read the following carefully before deciding to use this method:
833 * <li> geographical area codes change over time, and this method honors those changes;
834 * therefore, it doesn't guarantee the stability of the result it produces.
835 * <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
836 * typically requires the full national_number to be dialled in most regions).
837 * <li> most non-geographical numbers have no area codes, including numbers from non-geographical
839 * <li> some geographical numbers have no area codes.
841 * @param number the PhoneNumber object for which clients
842 * want to know the length of the area code.
843 * @return the length of area code of the PhoneNumber object
846 public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
847 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
848 if (metadata == null) {
851 // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
852 // zero, we assume it is a closed dialling plan with no area codes.
853 if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) {
857 if (!isNumberGeographical(number)) {
861 return getLengthOfNationalDestinationCode(number);
865 * Gets the length of the national destination code (NDC) from the
866 * PhoneNumber object passed in, so that clients could use it
867 * to split a national significant number into NDC and subscriber number. The NDC of a phone
868 * number is normally the first group of digit(s) right after the country calling code when the
869 * number is formatted in the international format, if there is a subscriber number part that
870 * follows. An example of how this could be used:
873 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
874 * PhoneNumber number = phoneUtil.parse("18002530000", "US");
875 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
876 * String nationalDestinationCode;
877 * String subscriberNumber;
879 * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
880 * if (nationalDestinationCodeLength > 0) {
881 * nationalDestinationCode = nationalSignificantNumber.substring(0,
882 * nationalDestinationCodeLength);
883 * subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
885 * nationalDestinationCode = "";
886 * subscriberNumber = nationalSignificantNumber;
890 * Refer to the unittests to see the difference between this function and
891 * {@link #getLengthOfGeographicalAreaCode}.
893 * @param number the PhoneNumber object for which clients
894 * want to know the length of the NDC.
895 * @return the length of NDC of the PhoneNumber object
898 public int getLengthOfNationalDestinationCode(PhoneNumber number) {
899 PhoneNumber copiedProto;
900 if (number.hasExtension()) {
901 // We don't want to alter the proto given to us, but we don't want to include the extension
902 // when we format it, so we copy it and clear the extension here.
903 copiedProto = new PhoneNumber();
904 copiedProto.mergeFrom(number);
905 copiedProto.clearExtension();
907 copiedProto = number;
910 String nationalSignificantNumber = format(copiedProto,
911 PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
912 String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
913 // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
914 // string (before the + symbol) and the second group will be the country calling code. The third
915 // group will be area code if it is not the last group.
916 if (numberGroups.length <= 3) {
920 if (getNumberType(number) == PhoneNumberType.MOBILE) {
921 // For example Argentinian mobile numbers, when formatted in the international format, are in
922 // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
923 // add the length of the second group (which is the mobile token), which also forms part of
924 // the national significant number. This assumes that the mobile token is always formatted
925 // separately from the rest of the phone number.
926 String mobileToken = getCountryMobileToken(number.getCountryCode());
927 if (!mobileToken.equals("")) {
928 return numberGroups[2].length() + numberGroups[3].length();
931 return numberGroups[2].length();
935 * Returns the mobile token for the provided country calling code if it has one, otherwise
936 * returns an empty string. A mobile token is a number inserted before the area code when dialing
937 * a mobile number from that country from abroad.
939 * @param countryCallingCode the country calling code for which we want the mobile token
940 * @return the mobile token, as a string, for the given country calling code
942 public static String getCountryMobileToken(int countryCallingCode) {
943 if (MOBILE_TOKEN_MAPPINGS.containsKey(countryCallingCode)) {
944 return MOBILE_TOKEN_MAPPINGS.get(countryCallingCode);
950 * Normalizes a string of characters representing a phone number by replacing all characters found
951 * in the accompanying map with the values therein, and stripping all other characters if
952 * removeNonMatches is true.
954 * @param number a string of characters representing a phone number
955 * @param normalizationReplacements a mapping of characters to what they should be replaced by in
956 * the normalized version of the phone number
957 * @param removeNonMatches indicates whether characters that are not able to be replaced
958 * should be stripped from the number. If this is false, they
959 * will be left unchanged in the number.
960 * @return the normalized string version of the phone number
962 private static String normalizeHelper(String number,
963 Map<Character, Character> normalizationReplacements,
964 boolean removeNonMatches) {
965 StringBuilder normalizedNumber = new StringBuilder(number.length());
966 for (int i = 0; i < number.length(); i++) {
967 char character = number.charAt(i);
968 Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
969 if (newDigit != null) {
970 normalizedNumber.append(newDigit);
971 } else if (!removeNonMatches) {
972 normalizedNumber.append(character);
974 // If neither of the above are true, we remove this character.
976 return normalizedNumber.toString();
980 * Sets or resets the PhoneNumberUtil singleton instance. If set to null, the next call to
981 * {@code getInstance()} will load (and return) the default instance.
983 // @VisibleForTesting
984 static synchronized void setInstance(PhoneNumberUtil util) {
989 * Convenience method to get a list of what regions the library has metadata for.
991 public Set<String> getSupportedRegions() {
992 return Collections.unmodifiableSet(supportedRegions);
996 * Convenience method to get a list of what global network calling codes the library has metadata
999 public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
1000 return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion);
1004 * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
1005 * parsing, or validation. The instance is loaded with phone number metadata for a number of most
1006 * commonly used regions.
1008 * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
1009 * multiple times will only result in one instance being created.
1011 * @return a PhoneNumberUtil instance
1013 public static synchronized PhoneNumberUtil getInstance() {
1014 if (instance == null) {
1015 setInstance(createInstance(DEFAULT_METADATA_LOADER));
1021 * Create a new {@link PhoneNumberUtil} instance to carry out international phone number
1022 * formatting, parsing, or validation. The instance is loaded with all metadata by
1023 * using the metadataLoader specified.
1025 * This method should only be used in the rare case in which you want to manage your own
1026 * metadata loading. Calling this method multiple times is very expensive, as each time
1027 * a new instance is created from scratch. When in doubt, use {@link #getInstance}.
1029 * @param metadataLoader Customized metadata loader. If null, default metadata loader will
1030 * be used. This should not be null.
1031 * @return a PhoneNumberUtil instance
1033 public static PhoneNumberUtil createInstance(MetadataLoader metadataLoader) {
1034 if (metadataLoader == null) {
1035 throw new IllegalArgumentException("metadataLoader could not be null.");
1037 return new PhoneNumberUtil(META_DATA_FILE_PREFIX, metadataLoader,
1038 CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
1042 * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
1043 * does not start with the national prefix.
1045 static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) {
1046 return nationalPrefixFormattingRule.length() == 0 ||
1047 FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches();
1051 * Tests whether a phone number has a geographical association. It checks if the number is
1052 * associated to a certain region in the country where it belongs to. Note that this doesn't
1053 * verify if the number is actually in use.
1055 * A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded, which performs a
1056 * looser check, since it only prevents cases where prefixes overlap for geocodable and
1057 * non-geocodable numbers. Also, if new phone number types were added, we should check if this
1058 * other method should be updated too.
1060 boolean isNumberGeographical(PhoneNumber phoneNumber) {
1061 PhoneNumberType numberType = getNumberType(phoneNumber);
1062 // TODO: Include mobile phone numbers from countries like Indonesia, which has some
1063 // mobile numbers that are geographical.
1064 return numberType == PhoneNumberType.FIXED_LINE ||
1065 numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
1069 * Helper function to check region code is not unknown or null.
1071 private boolean isValidRegionCode(String regionCode) {
1072 return regionCode != null && supportedRegions.contains(regionCode);
1076 * Helper function to check the country calling code is valid.
1078 private boolean hasValidCountryCallingCode(int countryCallingCode) {
1079 return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
1083 * Formats a phone number in the specified format using default rules. Note that this does not
1084 * promise to produce a phone number that the user can dial from where they are - although we do
1085 * format in either 'national' or 'international' format depending on what the client asks for, we
1086 * do not currently support a more abbreviated format, such as for users in the same "area" who
1087 * could potentially dial the number without area code. Note that if the phone number has a
1088 * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1089 * which formatting rules to apply so we return the national significant number with no formatting
1092 * @param number the phone number to be formatted
1093 * @param numberFormat the format the phone number should be formatted into
1094 * @return the formatted phone number
1096 public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
1097 if (number.getNationalNumber() == 0 && number.hasRawInput()) {
1098 // Unparseable numbers that kept their raw input just use that.
1099 // This is the only case where a number can be formatted as E164 without a
1100 // leading '+' symbol (but the original number wasn't parseable anyway).
1101 // TODO: Consider removing the 'if' above so that unparseable
1102 // strings without raw input format to the empty string instead of "+00"
1103 String rawInput = number.getRawInput();
1104 if (rawInput.length() > 0) {
1108 StringBuilder formattedNumber = new StringBuilder(20);
1109 format(number, numberFormat, formattedNumber);
1110 return formattedNumber.toString();
1114 * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
1115 * a parameter to decrease object creation when invoked many times.
1117 public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1118 StringBuilder formattedNumber) {
1119 // Clear the StringBuilder first.
1120 formattedNumber.setLength(0);
1121 int countryCallingCode = number.getCountryCode();
1122 String nationalSignificantNumber = getNationalSignificantNumber(number);
1124 if (numberFormat == PhoneNumberFormat.E164) {
1125 // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1126 // of the national number needs to be applied. Extensions are not formatted.
1127 formattedNumber.append(nationalSignificantNumber);
1128 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1132 if (!hasValidCountryCallingCode(countryCallingCode)) {
1133 formattedNumber.append(nationalSignificantNumber);
1136 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1137 // share a country calling code is contained by only one region for performance reasons. For
1138 // example, for NANPA regions it will be contained in the metadata for US.
1139 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1140 // Metadata cannot be null because the country calling code is valid (which means that the
1141 // region code cannot be ZZ and must be one of our supported region codes).
1142 PhoneMetadata metadata =
1143 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1144 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1145 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1146 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1150 * Formats a phone number in the specified format using client-defined formatting rules. Note that
1151 * if the phone number has a country calling code of zero or an otherwise invalid country calling
1152 * code, we cannot work out things like whether there should be a national prefix applied, or how
1153 * to format extensions, so we return the national significant number with no formatting applied.
1155 * @param number the phone number to be formatted
1156 * @param numberFormat the format the phone number should be formatted into
1157 * @param userDefinedFormats formatting rules specified by clients
1158 * @return the formatted phone number
1160 public String formatByPattern(PhoneNumber number,
1161 PhoneNumberFormat numberFormat,
1162 List<NumberFormat> userDefinedFormats) {
1163 int countryCallingCode = number.getCountryCode();
1164 String nationalSignificantNumber = getNationalSignificantNumber(number);
1165 if (!hasValidCountryCallingCode(countryCallingCode)) {
1166 return nationalSignificantNumber;
1168 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1169 // share a country calling code is contained by only one region for performance reasons. For
1170 // example, for NANPA regions it will be contained in the metadata for US.
1171 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1172 // Metadata cannot be null because the country calling code is valid
1173 PhoneMetadata metadata =
1174 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1176 StringBuilder formattedNumber = new StringBuilder(20);
1178 NumberFormat formattingPattern =
1179 chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1180 if (formattingPattern == null) {
1181 // If no pattern above is matched, we format the number as a whole.
1182 formattedNumber.append(nationalSignificantNumber);
1184 NumberFormat numFormatCopy = new NumberFormat();
1185 // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1186 // need to copy the rule so that subsequent replacements for different numbers have the
1187 // appropriate national prefix.
1188 numFormatCopy.mergeFrom(formattingPattern);
1189 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1190 if (nationalPrefixFormattingRule.length() > 0) {
1191 String nationalPrefix = metadata.getNationalPrefix();
1192 if (nationalPrefix.length() > 0) {
1193 // Replace $NP with national prefix and $FG with the first group ($1).
1194 nationalPrefixFormattingRule =
1195 NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
1196 nationalPrefixFormattingRule =
1197 FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
1198 numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1200 // We don't want to have a rule for how to format the national prefix if there isn't one.
1201 numFormatCopy.clearNationalPrefixFormattingRule();
1204 formattedNumber.append(
1205 formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
1207 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1208 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1209 return formattedNumber.toString();
1213 * Formats a phone number in national format for dialing using the carrier as specified in the
1214 * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1215 * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1216 * contains an empty string, returns the number in national format without any carrier code.
1218 * @param number the phone number to be formatted
1219 * @param carrierCode the carrier selection code to be used
1220 * @return the formatted phone number in national format for dialing using the carrier as
1221 * specified in the {@code carrierCode}
1223 public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
1224 int countryCallingCode = number.getCountryCode();
1225 String nationalSignificantNumber = getNationalSignificantNumber(number);
1226 if (!hasValidCountryCallingCode(countryCallingCode)) {
1227 return nationalSignificantNumber;
1230 // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1231 // share a country calling code is contained by only one region for performance reasons. For
1232 // example, for NANPA regions it will be contained in the metadata for US.
1233 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1234 // Metadata cannot be null because the country calling code is valid.
1235 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1237 StringBuilder formattedNumber = new StringBuilder(20);
1238 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1239 PhoneNumberFormat.NATIONAL, carrierCode));
1240 maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1241 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1243 return formattedNumber.toString();
1246 private PhoneMetadata getMetadataForRegionOrCallingCode(
1247 int countryCallingCode, String regionCode) {
1248 return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1249 ? getMetadataForNonGeographicalRegion(countryCallingCode)
1250 : getMetadataForRegion(regionCode);
1254 * Formats a phone number in national format for dialing using the carrier as specified in the
1255 * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1256 * use the {@code fallbackCarrierCode} passed in instead. If there is no
1257 * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1258 * string, return the number in national format without any carrier code.
1260 * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1261 * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
1263 * @param number the phone number to be formatted
1264 * @param fallbackCarrierCode the carrier selection code to be used, if none is found in the
1265 * phone number itself
1266 * @return the formatted phone number in national format for dialing using the number's
1267 * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1270 public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
1271 String fallbackCarrierCode) {
1272 return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
1273 ? number.getPreferredDomesticCarrierCode()
1274 : fallbackCarrierCode);
1278 * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1279 * specific region. If the number cannot be reached from the region (e.g. some countries block
1280 * toll-free numbers from being called outside of the country), the method returns an empty
1283 * @param number the phone number to be formatted
1284 * @param regionCallingFrom the region where the call is being placed
1285 * @param withFormatting whether the number should be returned with formatting symbols, such as
1286 * spaces and dashes.
1287 * @return the formatted phone number
1289 public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1290 boolean withFormatting) {
1291 int countryCallingCode = number.getCountryCode();
1292 if (!hasValidCountryCallingCode(countryCallingCode)) {
1293 return number.hasRawInput() ? number.getRawInput() : "";
1296 String formattedNumber = "";
1297 // Clear the extension, as that part cannot normally be dialed together with the main number.
1298 PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1299 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1300 PhoneNumberType numberType = getNumberType(numberNoExt);
1301 boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN);
1302 if (regionCallingFrom.equals(regionCode)) {
1303 boolean isFixedLineOrMobile =
1304 (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
1305 (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1306 // Carrier codes may be needed in some countries. We handle this here.
1307 if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
1309 formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
1310 } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
1311 formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
1312 ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1313 // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1314 // called within Brazil. Without that, most of the carriers won't connect the call.
1315 // Because of that, we return an empty string here.
1317 } else if (isValidNumber && regionCode.equals("HU")) {
1318 // The national format for HU numbers doesn't contain the national prefix, because that is
1319 // how numbers are normally written down. However, the national prefix is obligatory when
1320 // dialing from a mobile phone, except for short numbers. As a result, we add it back here
1321 // if it is a valid regular length phone number.
1323 getNddPrefixForRegion(regionCode, true /* strip non-digits */) +
1324 " " + format(numberNoExt, PhoneNumberFormat.NATIONAL);
1325 } else if (countryCallingCode == NANPA_COUNTRY_CODE) {
1326 // For NANPA countries, we output international format for numbers that can be dialed
1327 // internationally, since that always works, except for numbers which might potentially be
1328 // short numbers, which are always dialled in national format.
1329 PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom);
1330 if (canBeInternationallyDialled(numberNoExt) &&
1331 !isShorterThanPossibleNormalNumber(regionMetadata,
1332 getNationalSignificantNumber(numberNoExt))) {
1333 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1335 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1338 // For non-geographical countries, and Mexican and Chilean fixed line and mobile numbers, we
1339 // output international format for numbers that can be dialed internationally as that always
1341 if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
1342 // MX fixed line and mobile numbers should always be formatted in international format,
1343 // even when dialed within MX. For national format to work, a carrier code needs to be
1344 // used, and the correct carrier code depends on if the caller and callee are from the
1345 // same local area. It is trickier to get that to work correctly than using
1346 // international format, which is tested to work fine on all carriers.
1347 // CL fixed line numbers need the national prefix when dialing in the national format,
1348 // but don't have it when used for display. The reverse is true for mobile numbers.
1349 // As a result, we output them in the international format to make it work.
1350 ((regionCode.equals("MX") || regionCode.equals("CL")) &&
1351 isFixedLineOrMobile)) &&
1352 canBeInternationallyDialled(numberNoExt)) {
1353 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1355 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1358 } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) {
1359 // We assume that short numbers are not diallable from outside their region, so if a number
1360 // is not a valid regular length phone number, we treat it as if it cannot be internationally
1362 return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1363 : format(numberNoExt, PhoneNumberFormat.E164);
1365 return withFormatting ? formattedNumber
1366 : normalizeDiallableCharsOnly(formattedNumber);
1370 * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1371 * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1372 * same as that of the region where the number is from, then NATIONAL formatting will be applied.
1374 * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1375 * calling code, then we return the number with no formatting applied.
1377 * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1378 * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1379 * is used. For regions which have multiple international prefixes, the number in its
1380 * INTERNATIONAL format will be returned instead.
1382 * @param number the phone number to be formatted
1383 * @param regionCallingFrom the region where the call is being placed
1384 * @return the formatted phone number
1386 public String formatOutOfCountryCallingNumber(PhoneNumber number,
1387 String regionCallingFrom) {
1388 if (!isValidRegionCode(regionCallingFrom)) {
1389 logger.log(Level.WARNING,
1390 "Trying to format number from invalid region "
1392 + ". International formatting applied.");
1393 return format(number, PhoneNumberFormat.INTERNATIONAL);
1395 int countryCallingCode = number.getCountryCode();
1396 String nationalSignificantNumber = getNationalSignificantNumber(number);
1397 if (!hasValidCountryCallingCode(countryCallingCode)) {
1398 return nationalSignificantNumber;
1400 if (countryCallingCode == NANPA_COUNTRY_CODE) {
1401 if (isNANPACountry(regionCallingFrom)) {
1402 // For NANPA regions, return the national format for these regions but prefix it with the
1403 // country calling code.
1404 return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
1406 } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1407 // If regions share a country calling code, the country calling code need not be dialled.
1408 // This also applies when dialling within a region, so this if clause covers both these cases.
1409 // Technically this is the case for dialling from La Reunion to other overseas departments of
1410 // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
1411 // edge case for now and for those cases return the version including country calling code.
1412 // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
1413 return format(number, PhoneNumberFormat.NATIONAL);
1415 // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1416 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1417 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1419 // For regions that have multiple international prefixes, the international format of the
1420 // number is returned, unless there is a preferred international prefix.
1421 String internationalPrefixForFormatting = "";
1422 if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
1423 internationalPrefixForFormatting = internationalPrefix;
1424 } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1425 internationalPrefixForFormatting =
1426 metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1429 String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1430 // Metadata cannot be null because the country calling code is valid.
1431 PhoneMetadata metadataForRegion =
1432 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1433 String formattedNationalNumber =
1434 formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1435 StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1436 maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1438 if (internationalPrefixForFormatting.length() > 0) {
1439 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1440 .insert(0, internationalPrefixForFormatting);
1442 prefixNumberWithCountryCallingCode(countryCallingCode,
1443 PhoneNumberFormat.INTERNATIONAL,
1446 return formattedNumber.toString();
1450 * Formats a phone number using the original phone number format that the number is parsed from.
1451 * The original format is embedded in the country_code_source field of the PhoneNumber object
1452 * passed in. If such information is missing, the number will be formatted into the NATIONAL
1453 * format by default. When the number contains a leading zero and this is unexpected for this
1454 * country, or we don't have a formatting pattern for the number, the method returns the raw input
1455 * when it is available.
1457 * Note this method guarantees no digit will be inserted, removed or modified as a result of
1460 * @param number the phone number that needs to be formatted in its original number format
1461 * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number
1463 * @return the formatted phone number in its original number format
1465 public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
1466 if (number.hasRawInput() &&
1467 (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
1468 // We check if we have the formatting pattern because without that, we might format the number
1469 // as a group without national prefix.
1470 return number.getRawInput();
1472 if (!number.hasCountryCodeSource()) {
1473 return format(number, PhoneNumberFormat.NATIONAL);
1475 String formattedNumber;
1476 switch (number.getCountryCodeSource()) {
1477 case FROM_NUMBER_WITH_PLUS_SIGN:
1478 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1480 case FROM_NUMBER_WITH_IDD:
1481 formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1483 case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1484 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1486 case FROM_DEFAULT_COUNTRY:
1487 // Fall-through to default case.
1489 String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1490 // We strip non-digits from the NDD here, and from the raw input later, so that we can
1491 // compare them easily.
1492 String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1493 String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1494 if (nationalPrefix == null || nationalPrefix.length() == 0) {
1495 // If the region doesn't have a national prefix at all, we can safely return the national
1496 // format without worrying about a national prefix being added.
1497 formattedNumber = nationalFormat;
1500 // Otherwise, we check if the original number was entered with a national prefix.
1501 if (rawInputContainsNationalPrefix(
1502 number.getRawInput(), nationalPrefix, regionCode)) {
1503 // If so, we can safely return the national format.
1504 formattedNumber = nationalFormat;
1507 // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1508 // there is no metadata for the region.
1509 PhoneMetadata metadata = getMetadataForRegion(regionCode);
1510 String nationalNumber = getNationalSignificantNumber(number);
1511 NumberFormat formatRule =
1512 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1513 // The format rule could still be null here if the national number was 0 and there was no
1514 // raw input (this should not be possible for numbers generated by the phonenumber library
1515 // as they would also not have a country calling code and we would have exited earlier).
1516 if (formatRule == null) {
1517 formattedNumber = nationalFormat;
1520 // When the format we apply to this number doesn't contain national prefix, we can just
1521 // return the national format.
1522 // TODO: Refactor the code below with the code in
1523 // isNationalPrefixPresentIfRequired.
1524 String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1525 // We assume that the first-group symbol will never be _before_ the national prefix.
1526 int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1527 if (indexOfFirstGroup <= 0) {
1528 formattedNumber = nationalFormat;
1531 candidateNationalPrefixRule =
1532 candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1533 candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1534 if (candidateNationalPrefixRule.length() == 0) {
1535 // National prefix not used when formatting this number.
1536 formattedNumber = nationalFormat;
1539 // Otherwise, we need to remove the national prefix from our output.
1540 NumberFormat numFormatCopy = new NumberFormat();
1541 numFormatCopy.mergeFrom(formatRule);
1542 numFormatCopy.clearNationalPrefixFormattingRule();
1543 List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
1544 numberFormats.add(numFormatCopy);
1545 formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1548 String rawInput = number.getRawInput();
1549 // If no digit is inserted/removed/modified as a result of our formatting, we return the
1550 // formatted phone number; otherwise we return the raw input the user entered.
1551 if (formattedNumber != null && rawInput.length() > 0) {
1552 String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1553 String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1554 if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1555 formattedNumber = rawInput;
1558 return formattedNumber;
1561 // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1562 // national prefix is assumed to be in digits-only form.
1563 private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1564 String regionCode) {
1565 String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1566 if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1568 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1569 // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1570 // check the validity of the number if the assumed national prefix is removed (777123 won't
1571 // be valid in Japan).
1572 return isValidNumber(
1573 parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1574 } catch (NumberParseException e) {
1582 * Returns true if a number is from a region whose national significant number couldn't contain a
1583 * leading zero, but has the italian_leading_zero field set to true.
1585 private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
1586 return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
1589 private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1590 int countryCallingCode = number.getCountryCode();
1591 String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1592 PhoneMetadata metadata =
1593 getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
1594 if (metadata == null) {
1597 String nationalNumber = getNationalSignificantNumber(number);
1598 NumberFormat formatRule =
1599 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1600 return formatRule != null;
1604 * Formats a phone number for out-of-country dialing purposes.
1606 * Note that in this version, if the number was entered originally using alpha characters and
1607 * this version of the number is stored in raw_input, this representation of the number will be
1608 * used rather than the digit representation. Grouping information, as specified by characters
1609 * such as "-" and " ", will be retained.
1611 * <p><b>Caveats:</b></p>
1613 * <li> This will not produce good results if the country calling code is both present in the raw
1614 * input _and_ is the start of the national number. This is not a problem in the regions
1615 * which typically use alpha numbers.
1616 * <li> This will also not produce good results if the raw input has any grouping information
1617 * within the first three digits of the national number, and if the function needs to strip
1618 * preceding digits/words in the raw input before these digits. Normally people group the
1619 * first three digits together so this is not a huge problem - and will be fixed if it
1623 * @param number the phone number that needs to be formatted
1624 * @param regionCallingFrom the region where the call is being placed
1625 * @return the formatted phone number
1627 public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1628 String regionCallingFrom) {
1629 String rawInput = number.getRawInput();
1630 // If there is no raw input, then we can't keep alpha characters because there aren't any.
1631 // In this case, we return formatOutOfCountryCallingNumber.
1632 if (rawInput.length() == 0) {
1633 return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1635 int countryCode = number.getCountryCode();
1636 if (!hasValidCountryCallingCode(countryCode)) {
1639 // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1640 // the number in raw_input with the parsed number.
1641 // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1643 rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1644 // Now we trim everything before the first three digits in the parsed number. We choose three
1645 // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1646 // trim anything at all. Similarly, if the national number was less than three digits, we don't
1647 // trim anything at all.
1648 String nationalNumber = getNationalSignificantNumber(number);
1649 if (nationalNumber.length() > 3) {
1650 int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1651 if (firstNationalNumberDigit != -1) {
1652 rawInput = rawInput.substring(firstNationalNumberDigit);
1655 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1656 if (countryCode == NANPA_COUNTRY_CODE) {
1657 if (isNANPACountry(regionCallingFrom)) {
1658 return countryCode + " " + rawInput;
1660 } else if (metadataForRegionCallingFrom != null &&
1661 countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1662 NumberFormat formattingPattern =
1663 chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
1665 if (formattingPattern == null) {
1666 // If no pattern above is matched, we format the original input.
1669 NumberFormat newFormat = new NumberFormat();
1670 newFormat.mergeFrom(formattingPattern);
1671 // The first group is the first group of digits that the user wrote together.
1672 newFormat.setPattern("(\\d+)(.*)");
1673 // Here we just concatenate them back together after the national prefix has been fixed.
1674 newFormat.setFormat("$1$2");
1675 // Now we format using this pattern instead of the default pattern, but with the national
1676 // prefix prefixed if necessary.
1677 // This will not work in the cases where the pattern (and not the leading digits) decide
1678 // whether a national prefix needs to be used, since we have overridden the pattern to match
1679 // anything, but that is not the case in the metadata to date.
1680 return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
1682 String internationalPrefixForFormatting = "";
1683 // If an unsupported region-calling-from is entered, or a country with multiple international
1684 // prefixes, the international format of the number is returned, unless there is a preferred
1685 // international prefix.
1686 if (metadataForRegionCallingFrom != null) {
1687 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1688 internationalPrefixForFormatting =
1689 UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1690 ? internationalPrefix
1691 : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1693 StringBuilder formattedNumber = new StringBuilder(rawInput);
1694 String regionCode = getRegionCodeForCountryCode(countryCode);
1695 // Metadata cannot be null because the country calling code is valid.
1696 PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1697 maybeAppendFormattedExtension(number, metadataForRegion,
1698 PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1699 if (internationalPrefixForFormatting.length() > 0) {
1700 formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1701 .insert(0, internationalPrefixForFormatting);
1703 // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1704 // region chosen has multiple international dialling prefixes.
1705 logger.log(Level.WARNING,
1706 "Trying to format number from invalid region "
1708 + ". International formatting applied.");
1709 prefixNumberWithCountryCallingCode(countryCode,
1710 PhoneNumberFormat.INTERNATIONAL,
1713 return formattedNumber.toString();
1717 * Gets the national significant number of the a phone number. Note a national significant number
1718 * doesn't contain a national prefix or any formatting.
1720 * @param number the phone number for which the national significant number is needed
1721 * @return the national significant number of the PhoneNumber object passed in
1723 public String getNationalSignificantNumber(PhoneNumber number) {
1724 // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
1725 StringBuilder nationalNumber = new StringBuilder();
1726 if (number.isItalianLeadingZero()) {
1727 char[] zeros = new char[number.getNumberOfLeadingZeros()];
1728 Arrays.fill(zeros, '0');
1729 nationalNumber.append(new String(zeros));
1731 nationalNumber.append(number.getNationalNumber());
1732 return nationalNumber.toString();
1736 * A helper function that is used by format and formatByPattern.
1738 private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1739 PhoneNumberFormat numberFormat,
1740 StringBuilder formattedNumber) {
1741 switch (numberFormat) {
1743 formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1746 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1749 formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1750 .insert(0, RFC3966_PREFIX);
1758 // Simple wrapper of formatNsn for the common case of no carrier code.
1759 private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1760 return formatNsn(number, metadata, numberFormat, null);
1763 // Note in some regions, the national number can be written in two completely different ways
1764 // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
1765 // numberFormat parameter here is used to specify which format to use for those cases. If a
1766 // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1767 private String formatNsn(String number,
1768 PhoneMetadata metadata,
1769 PhoneNumberFormat numberFormat,
1770 String carrierCode) {
1771 List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
1772 // When the intlNumberFormats exists, we use that to format national number for the
1773 // INTERNATIONAL format instead of using the numberDesc.numberFormats.
1774 List<NumberFormat> availableFormats =
1775 (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
1776 ? metadata.numberFormats()
1777 : metadata.intlNumberFormats();
1778 NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1779 return (formattingPattern == null)
1781 : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
1784 NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1785 String nationalNumber) {
1786 for (NumberFormat numFormat : availableFormats) {
1787 int size = numFormat.leadingDigitsPatternSize();
1788 if (size == 0 || regexCache.getPatternForRegex(
1789 // We always use the last leading_digits_pattern, as it is the most detailed.
1790 numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
1791 Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1800 // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1801 String formatNsnUsingPattern(String nationalNumber,
1802 NumberFormat formattingPattern,
1803 PhoneNumberFormat numberFormat) {
1804 return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
1807 // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
1809 private String formatNsnUsingPattern(String nationalNumber,
1810 NumberFormat formattingPattern,
1811 PhoneNumberFormat numberFormat,
1812 String carrierCode) {
1813 String numberFormatRule = formattingPattern.getFormat();
1815 regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1816 String formattedNationalNumber = "";
1817 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1818 carrierCode != null && carrierCode.length() > 0 &&
1819 formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1820 // Replace the $CC in the formatting rule with the desired carrier code.
1821 String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1822 carrierCodeFormattingRule =
1823 CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
1824 // Now replace the $FG in the formatting rule with the first group and the carrier code
1825 // combined in the appropriate way.
1826 numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
1827 .replaceFirst(carrierCodeFormattingRule);
1828 formattedNationalNumber = m.replaceAll(numberFormatRule);
1830 // Use the national prefix formatting rule instead.
1831 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1832 if (numberFormat == PhoneNumberFormat.NATIONAL &&
1833 nationalPrefixFormattingRule != null &&
1834 nationalPrefixFormattingRule.length() > 0) {
1835 Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
1836 formattedNationalNumber =
1837 m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
1839 formattedNationalNumber = m.replaceAll(numberFormatRule);
1842 if (numberFormat == PhoneNumberFormat.RFC3966) {
1843 // Strip any leading punctuation.
1844 Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
1845 if (matcher.lookingAt()) {
1846 formattedNationalNumber = matcher.replaceFirst("");
1848 // Replace the rest with a dash between each number group.
1849 formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
1851 return formattedNationalNumber;
1855 * Gets a valid number for the specified region.
1857 * @param regionCode the region for which an example number is needed
1858 * @return a valid fixed-line number for the specified region. Returns null when the metadata
1859 * does not contain such information, or the region 001 is passed in. For 001 (representing
1860 * non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
1862 public PhoneNumber getExampleNumber(String regionCode) {
1863 return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
1867 * Gets a valid number for the specified region and number type.
1869 * @param regionCode the region for which an example number is needed
1870 * @param type the type of number that is needed
1871 * @return a valid number for the specified region and type. Returns null when the metadata
1872 * does not contain such information or if an invalid region or region 001 was entered.
1873 * For 001 (representing non-geographical numbers), call
1874 * {@link #getExampleNumberForNonGeoEntity} instead.
1876 public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
1877 // Check the region code is valid.
1878 if (!isValidRegionCode(regionCode)) {
1879 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
1882 PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
1884 if (desc.hasExampleNumber()) {
1885 return parse(desc.getExampleNumber(), regionCode);
1887 } catch (NumberParseException e) {
1888 logger.log(Level.SEVERE, e.toString());
1894 * Gets a valid number for the specified country calling code for a non-geographical entity.
1896 * @param countryCallingCode the country calling code for a non-geographical entity
1897 * @return a valid number for the non-geographical entity. Returns null when the metadata
1898 * does not contain such information, or the country calling code passed in does not belong
1899 * to a non-geographical entity.
1901 public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
1902 PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
1903 if (metadata != null) {
1904 PhoneNumberDesc desc = metadata.getGeneralDesc();
1906 if (desc.hasExampleNumber()) {
1907 return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
1909 } catch (NumberParseException e) {
1910 logger.log(Level.SEVERE, e.toString());
1913 logger.log(Level.WARNING,
1914 "Invalid or unknown country calling code provided: " + countryCallingCode);
1920 * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1921 * an extension specified.
1923 private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
1924 PhoneNumberFormat numberFormat,
1925 StringBuilder formattedNumber) {
1926 if (number.hasExtension() && number.getExtension().length() > 0) {
1927 if (numberFormat == PhoneNumberFormat.RFC3966) {
1928 formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
1930 if (metadata.hasPreferredExtnPrefix()) {
1931 formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
1933 formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
1939 PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
1942 return metadata.getPremiumRate();
1944 return metadata.getTollFree();
1946 return metadata.getMobile();
1948 case FIXED_LINE_OR_MOBILE:
1949 return metadata.getFixedLine();
1951 return metadata.getSharedCost();
1953 return metadata.getVoip();
1954 case PERSONAL_NUMBER:
1955 return metadata.getPersonalNumber();
1957 return metadata.getPager();
1959 return metadata.getUan();
1961 return metadata.getVoicemail();
1963 return metadata.getGeneralDesc();
1968 * Gets the type of a phone number.
1970 * @param number the phone number that we want to know the type
1971 * @return the type of the phone number
1973 public PhoneNumberType getNumberType(PhoneNumber number) {
1974 String regionCode = getRegionCodeForNumber(number);
1975 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
1976 if (metadata == null) {
1977 return PhoneNumberType.UNKNOWN;
1979 String nationalSignificantNumber = getNationalSignificantNumber(number);
1980 return getNumberTypeHelper(nationalSignificantNumber, metadata);
1983 private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
1984 if (!isNumberMatchingDesc(nationalNumber, metadata.getGeneralDesc())) {
1985 return PhoneNumberType.UNKNOWN;
1988 if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
1989 return PhoneNumberType.PREMIUM_RATE;
1991 if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
1992 return PhoneNumberType.TOLL_FREE;
1994 if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
1995 return PhoneNumberType.SHARED_COST;
1997 if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
1998 return PhoneNumberType.VOIP;
2000 if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
2001 return PhoneNumberType.PERSONAL_NUMBER;
2003 if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
2004 return PhoneNumberType.PAGER;
2006 if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
2007 return PhoneNumberType.UAN;
2009 if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
2010 return PhoneNumberType.VOICEMAIL;
2013 boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
2015 if (metadata.isSameMobileAndFixedLinePattern()) {
2016 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2017 } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2018 return PhoneNumberType.FIXED_LINE_OR_MOBILE;
2020 return PhoneNumberType.FIXED_LINE;
2022 // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
2023 // mobile and fixed line aren't the same.
2024 if (!metadata.isSameMobileAndFixedLinePattern() &&
2025 isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
2026 return PhoneNumberType.MOBILE;
2028 return PhoneNumberType.UNKNOWN;
2032 * Returns the metadata for the given region code or {@code null} if the region code is invalid
2035 PhoneMetadata getMetadataForRegion(String regionCode) {
2036 if (!isValidRegionCode(regionCode)) {
2039 synchronized (regionToMetadataMap) {
2040 if (!regionToMetadataMap.containsKey(regionCode)) {
2041 // The regionCode here will be valid and won't be '001', so we don't need to worry about
2042 // what to pass in for the country calling code.
2043 loadMetadataFromFile(currentFilePrefix, regionCode, 0, metadataLoader);
2046 return regionToMetadataMap.get(regionCode);
2049 PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
2050 synchronized (countryCodeToNonGeographicalMetadataMap) {
2051 if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
2054 if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
2055 loadMetadataFromFile(
2056 currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode, metadataLoader);
2059 return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
2062 boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2063 Matcher possibleNumberPatternMatcher =
2064 regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
2065 .matcher(nationalNumber);
2066 return possibleNumberPatternMatcher.matches();
2069 boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2070 Matcher nationalNumberPatternMatcher =
2071 regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
2072 .matcher(nationalNumber);
2073 return isNumberPossibleForDesc(nationalNumber, numberDesc) &&
2074 nationalNumberPatternMatcher.matches();
2078 * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
2079 * is actually in use, which is impossible to tell by just looking at a number itself.
2081 * @param number the phone number that we want to validate
2082 * @return a boolean that indicates whether the number is of a valid pattern
2084 public boolean isValidNumber(PhoneNumber number) {
2085 String regionCode = getRegionCodeForNumber(number);
2086 return isValidNumberForRegion(number, regionCode);
2090 * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
2091 * is actually in use, which is impossible to tell by just looking at a number itself. If the
2092 * country calling code is not the same as the country calling code for the region, this
2093 * immediately exits with false. After this, the specific number pattern rules for the region are
2094 * examined. This is useful for determining for example whether a particular number is valid for
2095 * Canada, rather than just a valid NANPA number.
2096 * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2097 * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2098 * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2101 * @param number the phone number that we want to validate
2102 * @param regionCode the region that we want to validate the phone number for
2103 * @return a boolean that indicates whether the number is of a valid pattern
2105 public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2106 int countryCode = number.getCountryCode();
2107 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2108 if ((metadata == null) ||
2109 (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
2110 countryCode != getCountryCodeForValidRegion(regionCode))) {
2111 // Either the region code was invalid, or the country calling code for this number does not
2112 // match that of the region code.
2115 String nationalSignificantNumber = getNationalSignificantNumber(number);
2116 return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
2120 * Returns the region where a phone number is from. This could be used for geocoding at the region
2123 * @param number the phone number whose origin we want to know
2124 * @return the region where the phone number is from, or null if no region matches this calling
2127 public String getRegionCodeForNumber(PhoneNumber number) {
2128 int countryCode = number.getCountryCode();
2129 List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
2130 if (regions == null) {
2131 String numberString = getNationalSignificantNumber(number);
2132 logger.log(Level.WARNING,
2133 "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
2136 if (regions.size() == 1) {
2137 return regions.get(0);
2139 return getRegionCodeForNumberFromRegionList(number, regions);
2143 private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
2144 List<String> regionCodes) {
2145 String nationalNumber = getNationalSignificantNumber(number);
2146 for (String regionCode : regionCodes) {
2147 // If leadingDigits is present, use this. Otherwise, do full validation.
2148 // Metadata cannot be null because the region codes come from the country calling code map.
2149 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2150 if (metadata.hasLeadingDigits()) {
2151 if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
2152 .matcher(nationalNumber).lookingAt()) {
2155 } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
2163 * Returns the region code that matches the specific country calling code. In the case of no
2164 * region code being found, ZZ will be returned. In the case of multiple regions, the one
2165 * designated in the metadata as the "main" region for this calling code will be returned. If the
2166 * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
2167 * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
2168 * the value for World in the UN M.49 schema).
2170 public String getRegionCodeForCountryCode(int countryCallingCode) {
2171 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2172 return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
2176 * Returns a list with the region codes that match the specific country calling code. For
2177 * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2178 * of no region code being found, an empty list is returned.
2180 public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2181 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2182 return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2187 * Returns the country calling code for a specific region. For example, this would be 1 for the
2188 * United States, and 64 for New Zealand.
2190 * @param regionCode the region that we want to get the country calling code for
2191 * @return the country calling code for the region denoted by regionCode
2193 public int getCountryCodeForRegion(String regionCode) {
2194 if (!isValidRegionCode(regionCode)) {
2195 logger.log(Level.WARNING,
2196 "Invalid or missing region code ("
2197 + ((regionCode == null) ? "null" : regionCode)
2201 return getCountryCodeForValidRegion(regionCode);
2205 * Returns the country calling code for a specific region. For example, this would be 1 for the
2206 * United States, and 64 for New Zealand. Assumes the region is already valid.
2208 * @param regionCode the region that we want to get the country calling code for
2209 * @return the country calling code for the region denoted by regionCode
2210 * @throws IllegalArgumentException if the region is invalid
2212 private int getCountryCodeForValidRegion(String regionCode) {
2213 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2214 if (metadata == null) {
2215 throw new IllegalArgumentException("Invalid region code: " + regionCode);
2217 return metadata.getCountryCode();
2221 * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2222 * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2223 * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2224 * present, we return null.
2226 * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2227 * national dialling prefix is used only for certain types of numbers. Use the library's
2228 * formatting functions to prefix the national prefix when required.
2230 * @param regionCode the region that we want to get the dialling prefix for
2231 * @param stripNonDigits true to strip non-digits from the national dialling prefix
2232 * @return the dialling prefix for the region denoted by regionCode
2234 public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2235 PhoneMetadata metadata = getMetadataForRegion(regionCode);
2236 if (metadata == null) {
2237 logger.log(Level.WARNING,
2238 "Invalid or missing region code ("
2239 + ((regionCode == null) ? "null" : regionCode)
2243 String nationalPrefix = metadata.getNationalPrefix();
2244 // If no national prefix was found, we return null.
2245 if (nationalPrefix.length() == 0) {
2248 if (stripNonDigits) {
2249 // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2250 // to be removed here as well.
2251 nationalPrefix = nationalPrefix.replace("~", "");
2253 return nationalPrefix;
2257 * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
2259 * @return true if regionCode is one of the regions under NANPA
2261 public boolean isNANPACountry(String regionCode) {
2262 return nanpaRegions.contains(regionCode);
2266 * Checks whether the country calling code is from a region whose national significant number
2267 * could contain a leading zero. An example of such a region is Italy. Returns false if no
2268 * metadata for the country is found.
2270 boolean isLeadingZeroPossible(int countryCallingCode) {
2271 PhoneMetadata mainMetadataForCallingCode =
2272 getMetadataForRegionOrCallingCode(countryCallingCode,
2273 getRegionCodeForCountryCode(countryCallingCode));
2274 if (mainMetadataForCallingCode == null) {
2277 return mainMetadataForCallingCode.isLeadingZeroPossible();
2281 * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2282 * number will start with at least 3 digits and will have three or more alpha characters. This
2283 * does not do region-specific checks - to work out if this number is actually valid for a region,
2284 * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2285 * {@link #isValidNumber} should be used.
2287 * @param number the number that needs to be checked
2288 * @return true if the number is a valid vanity number
2290 public boolean isAlphaNumber(String number) {
2291 if (!isViablePhoneNumber(number)) {
2292 // Number is too short, or doesn't match the basic phone number pattern.
2295 StringBuilder strippedNumber = new StringBuilder(number);
2296 maybeStripExtension(strippedNumber);
2297 return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2301 * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2302 * for failure, this method returns a boolean value.
2303 * @param number the number that needs to be checked
2304 * @return true if the number is possible
2306 public boolean isPossibleNumber(PhoneNumber number) {
2307 return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
2311 * Helper method to check a number against a particular pattern and determine whether it matches,
2312 * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
2313 * and 10 are possible, and a number in between these possible lengths is entered, such as of
2314 * length 8, this will return TOO_LONG.
2316 private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
2317 Matcher numberMatcher = numberPattern.matcher(number);
2318 if (numberMatcher.matches()) {
2319 return ValidationResult.IS_POSSIBLE;
2321 if (numberMatcher.lookingAt()) {
2322 return ValidationResult.TOO_LONG;
2324 return ValidationResult.TOO_SHORT;
2329 * Helper method to check whether a number is too short to be a regular length phone number in a
2332 private boolean isShorterThanPossibleNormalNumber(PhoneMetadata regionMetadata, String number) {
2333 Pattern possibleNumberPattern = regexCache.getPatternForRegex(
2334 regionMetadata.getGeneralDesc().getPossibleNumberPattern());
2335 return testNumberLengthAgainstPattern(possibleNumberPattern, number) ==
2336 ValidationResult.TOO_SHORT;
2340 * Check whether a phone number is a possible number. It provides a more lenient check than
2341 * {@link #isValidNumber} in the following sense:
2343 * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
2344 * digits of the number.
2345 * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2346 * applies to all types of phone numbers in a region. Therefore, it is much faster than
2348 * <li> For fixed line numbers, many regions have the concept of area code, which together with
2349 * subscriber number constitute the national significant number. It is sometimes okay to dial
2350 * the subscriber number only when dialing in the same area. This function will return
2351 * true if the subscriber-number-only version is passed in. On the other hand, because
2352 * isValidNumber validates using information on both starting digits (for fixed line
2353 * numbers, that would most likely be area codes) and length (obviously includes the
2354 * length of area codes for fixed line numbers), it will return false for the
2355 * subscriber-number-only version.
2357 * @param number the number that needs to be checked
2358 * @return a ValidationResult object which indicates whether the number is possible
2360 public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2361 String nationalNumber = getNationalSignificantNumber(number);
2362 int countryCode = number.getCountryCode();
2363 // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
2364 // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
2365 // valid. This would need to be revisited if the possible number pattern ever differed between
2366 // various regions within those plans.
2367 if (!hasValidCountryCallingCode(countryCode)) {
2368 return ValidationResult.INVALID_COUNTRY_CODE;
2370 String regionCode = getRegionCodeForCountryCode(countryCode);
2371 // Metadata cannot be null because the country calling code is valid.
2372 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2373 Pattern possibleNumberPattern =
2374 regexCache.getPatternForRegex(metadata.getGeneralDesc().getPossibleNumberPattern());
2375 return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
2379 * Check whether a phone number is a possible number given a number in the form of a string, and
2380 * the region where the number could be dialed from. It provides a more lenient check than
2381 * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
2383 * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
2384 * with the resultant PhoneNumber object.
2386 * @param number the number that needs to be checked, in the form of a string
2387 * @param regionDialingFrom the region that we are expecting the number to be dialed from.
2388 * Note this is different from the region where the number belongs. For example, the number
2389 * +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2390 * dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2391 * region which uses an international dialling prefix of 00. When it is written as
2392 * 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2393 * can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
2395 * @return true if the number is possible
2397 public boolean isPossibleNumber(String number, String regionDialingFrom) {
2399 return isPossibleNumber(parse(number, regionDialingFrom));
2400 } catch (NumberParseException e) {
2406 * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2407 * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2408 * the PhoneNumber object passed in will not be modified.
2409 * @param number a PhoneNumber object which contains a number that is too long to be valid.
2410 * @return true if a valid phone number can be successfully extracted.
2412 public boolean truncateTooLongNumber(PhoneNumber number) {
2413 if (isValidNumber(number)) {
2416 PhoneNumber numberCopy = new PhoneNumber();
2417 numberCopy.mergeFrom(number);
2418 long nationalNumber = number.getNationalNumber();
2420 nationalNumber /= 10;
2421 numberCopy.setNationalNumber(nationalNumber);
2422 if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
2423 nationalNumber == 0) {
2426 } while (!isValidNumber(numberCopy));
2427 number.setNationalNumber(nationalNumber);
2432 * Gets an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
2434 * @param regionCode the region where the phone number is being entered
2435 * @return an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2436 * to format phone numbers in the specific region "as you type"
2438 public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
2439 return new AsYouTypeFormatter(regionCode);
2442 // Extracts country calling code from fullNumber, returns it and places the remaining number in
2443 // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2444 // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2446 int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2447 if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2448 // Country codes do not begin with a '0'.
2451 int potentialCountryCode;
2452 int numberLength = fullNumber.length();
2453 for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
2454 potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2455 if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
2456 nationalNumber.append(fullNumber.substring(i));
2457 return potentialCountryCode;
2464 * Tries to extract a country calling code from a number. This method will return zero if no
2465 * country calling code is considered to be present. Country calling codes are extracted in the
2468 * <li> by stripping the international dialing prefix of the region the person is dialing from,
2469 * if this is present in the number, and looking at the next digits
2470 * <li> by stripping the '+' sign if present and then looking at the next digits
2471 * <li> by comparing the start of the number and the country calling code of the default region.
2472 * If the number is not considered possible for the numbering plan of the default region
2473 * initially, but starts with the country calling code of this region, validation will be
2474 * reattempted after stripping this country calling code. If this number is considered a
2475 * possible number, then the first digits will be considered the country calling code and
2478 * It will throw a NumberParseException if the number starts with a '+' but the country calling
2479 * code supplied after this does not match that of any known region.
2481 * @param number non-normalized telephone number that we wish to extract a country calling
2482 * code from - may begin with '+'
2483 * @param defaultRegionMetadata metadata about the region this number may be from
2484 * @param nationalNumber a string buffer to store the national significant number in, in the case
2485 * that a country calling code was extracted. The number is appended to any existing contents.
2486 * If no country calling code was extracted, this will be left unchanged.
2487 * @param keepRawInput true if the country_code_source and preferred_carrier_code fields of
2488 * phoneNumber should be populated.
2489 * @param phoneNumber the PhoneNumber object where the country_code and country_code_source need
2490 * to be populated. Note the country_code is always populated, whereas country_code_source is
2491 * only populated when keepCountryCodeSource is true.
2492 * @return the country calling code extracted or 0 if none could be extracted
2494 // @VisibleForTesting
2495 int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
2496 StringBuilder nationalNumber, boolean keepRawInput,
2497 PhoneNumber phoneNumber)
2498 throws NumberParseException {
2499 if (number.length() == 0) {
2502 StringBuilder fullNumber = new StringBuilder(number);
2503 // Set the default prefix to be something that will never match.
2504 String possibleCountryIddPrefix = "NonMatch";
2505 if (defaultRegionMetadata != null) {
2506 possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
2509 CountryCodeSource countryCodeSource =
2510 maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
2512 phoneNumber.setCountryCodeSource(countryCodeSource);
2514 if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2515 if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
2516 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
2517 "Phone number had an IDD, but after this was not "
2518 + "long enough to be a viable phone number.");
2520 int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
2521 if (potentialCountryCode != 0) {
2522 phoneNumber.setCountryCode(potentialCountryCode);
2523 return potentialCountryCode;
2526 // If this fails, they must be using a strange country calling code that we don't recognize,
2527 // or that doesn't exist.
2528 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2529 "Country calling code supplied was not recognised.");
2530 } else if (defaultRegionMetadata != null) {
2531 // Check to see if the number starts with the country calling code for the default region. If
2532 // so, we remove the country calling code, and do some checks on the validity of the number
2533 // before and after.
2534 int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2535 String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2536 String normalizedNumber = fullNumber.toString();
2537 if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2538 StringBuilder potentialNationalNumber =
2539 new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
2540 PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2541 Pattern validNumberPattern =
2542 regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
2543 maybeStripNationalPrefixAndCarrierCode(
2544 potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2545 Pattern possibleNumberPattern =
2546 regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
2547 // If the number was not valid before but is valid now, or if it was too long before, we
2548 // consider the number with the country calling code stripped to be a better result and
2549 // keep that instead.
2550 if ((!validNumberPattern.matcher(fullNumber).matches() &&
2551 validNumberPattern.matcher(potentialNationalNumber).matches()) ||
2552 testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
2553 == ValidationResult.TOO_LONG) {
2554 nationalNumber.append(potentialNationalNumber);
2556 phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
2558 phoneNumber.setCountryCode(defaultCountryCode);
2559 return defaultCountryCode;
2563 // No country calling code present.
2564 phoneNumber.setCountryCode(0);
2569 * Strips the IDD from the start of the number if present. Helper function used by
2570 * maybeStripInternationalPrefixAndNormalize.
2572 private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
2573 Matcher m = iddPattern.matcher(number);
2574 if (m.lookingAt()) {
2575 int matchEnd = m.end();
2576 // Only strip this if the first digit after the match is not a 0, since country calling codes
2577 // cannot begin with 0.
2578 Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
2579 if (digitMatcher.find()) {
2580 String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
2581 if (normalizedGroup.equals("0")) {
2585 number.delete(0, matchEnd);
2592 * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2593 * the resulting number, and indicates if an international prefix was present.
2595 * @param number the non-normalized telephone number that we wish to strip any international
2596 * dialing prefix from.
2597 * @param possibleIddPrefix the international direct dialing prefix from the region we
2598 * think this number may be dialed in
2599 * @return the corresponding CountryCodeSource if an international dialing prefix could be
2600 * removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2601 * not seem to be in international format.
2603 // @VisibleForTesting
2604 CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2605 StringBuilder number,
2606 String possibleIddPrefix) {
2607 if (number.length() == 0) {
2608 return CountryCodeSource.FROM_DEFAULT_COUNTRY;
2610 // Check to see if the number begins with one or more plus signs.
2611 Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2612 if (m.lookingAt()) {
2613 number.delete(0, m.end());
2614 // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
2616 return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
2618 // Attempt to parse the first digits as an international prefix.
2619 Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
2621 return parsePrefixAsIdd(iddPattern, number)
2622 ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2623 : CountryCodeSource.FROM_DEFAULT_COUNTRY;
2627 * Strips any national prefix (such as 0, 1) present in the number provided.
2629 * @param number the normalized telephone number that we wish to strip any national
2630 * dialing prefix from
2631 * @param metadata the metadata for the region that we think this number is from
2632 * @param carrierCode a place to insert the carrier code if one is extracted
2633 * @return true if a national prefix or carrier code (or both) could be extracted.
2635 // @VisibleForTesting
2636 boolean maybeStripNationalPrefixAndCarrierCode(
2637 StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
2638 int numberLength = number.length();
2639 String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
2640 if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
2641 // Early return for numbers of zero length.
2644 // Attempt to parse the first digits as a national prefix.
2645 Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
2646 if (prefixMatcher.lookingAt()) {
2647 Pattern nationalNumberRule =
2648 regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
2649 // Check if the original number is viable.
2650 boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
2651 // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
2652 // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
2653 // remove the national prefix.
2654 int numOfGroups = prefixMatcher.groupCount();
2655 String transformRule = metadata.getNationalPrefixTransformRule();
2656 if (transformRule == null || transformRule.length() == 0 ||
2657 prefixMatcher.group(numOfGroups) == null) {
2658 // If the original number was viable, and the resultant number is not, we return.
2659 if (isViableOriginalNumber &&
2660 !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
2663 if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
2664 carrierCode.append(prefixMatcher.group(1));
2666 number.delete(0, prefixMatcher.end());
2669 // Check that the resultant number is still viable. If not, return. Check this by copying
2670 // the string buffer and making the transformation on the copy first.
2671 StringBuilder transformedNumber = new StringBuilder(number);
2672 transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
2673 if (isViableOriginalNumber &&
2674 !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
2677 if (carrierCode != null && numOfGroups > 1) {
2678 carrierCode.append(prefixMatcher.group(1));
2680 number.replace(0, number.length(), transformedNumber.toString());
2688 * Strips any extension (as in, the part of the number dialled after the call is connected,
2689 * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
2691 * @param number the non-normalized telephone number that we wish to strip the extension from
2692 * @return the phone extension
2694 // @VisibleForTesting
2695 String maybeStripExtension(StringBuilder number) {
2696 Matcher m = EXTN_PATTERN.matcher(number);
2697 // If we find a potential extension, and the number preceding this is a viable number, we assume
2698 // it is an extension.
2699 if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
2700 // The numbers are captured into groups in the regular expression.
2701 for (int i = 1, length = m.groupCount(); i <= length; i++) {
2702 if (m.group(i) != null) {
2703 // We go through the capturing groups until we find one that captured some digits. If none
2704 // did, then we will return the empty string.
2705 String extension = m.group(i);
2706 number.delete(m.start(), number.length());
2715 * Checks to see that the region code used is valid, or if it is not valid, that the number to
2716 * parse starts with a + symbol so that we can attempt to infer the region from the number.
2717 * Returns false if it cannot use the region provided and the region cannot be inferred.
2719 private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
2720 if (!isValidRegionCode(defaultRegion)) {
2721 // If the number is null or empty, we can't infer the region.
2722 if ((numberToParse == null) || (numberToParse.length() == 0) ||
2723 !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
2731 * Parses a string and returns it in proto buffer format. This method will throw a
2732 * {@link com.google.i18n.phonenumbers.NumberParseException} if the number is not considered to be
2733 * a possible number. Note that validation of whether the number is actually a valid number for a
2734 * particular region is not performed. This can be done separately with {@link #isValidNumber}.
2736 * @param numberToParse number that we are attempting to parse. This can contain formatting
2737 * such as +, ( and -, as well as a phone number extension. It can also
2738 * be provided in RFC3966 format.
2739 * @param defaultRegion region that we are expecting the number to be from. This is only used
2740 * if the number being parsed is not written in international format.
2741 * The country_code for the number in this case would be stored as that
2742 * of the default region supplied. If the number is guaranteed to
2743 * start with a '+' followed by the country calling code, then
2744 * "ZZ" or null can be supplied.
2745 * @return a phone number proto buffer filled with the parsed number
2746 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2747 * no default region was supplied and the number is not in
2748 * international format (does not start with +)
2750 public PhoneNumber parse(String numberToParse, String defaultRegion)
2751 throws NumberParseException {
2752 PhoneNumber phoneNumber = new PhoneNumber();
2753 parse(numberToParse, defaultRegion, phoneNumber);
2758 * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
2759 * decrease object creation when invoked many times.
2761 public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
2762 throws NumberParseException {
2763 parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
2767 * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
2768 * in that it always populates the raw_input field of the protocol buffer with numberToParse as
2769 * well as the country_code_source field.
2771 * @param numberToParse number that we are attempting to parse. This can contain formatting
2772 * such as +, ( and -, as well as a phone number extension.
2773 * @param defaultRegion region that we are expecting the number to be from. This is only used
2774 * if the number being parsed is not written in international format.
2775 * The country calling code for the number in this case would be stored
2776 * as that of the default region supplied.
2777 * @return a phone number proto buffer filled with the parsed number
2778 * @throws NumberParseException if the string is not considered to be a viable phone number or if
2779 * no default region was supplied
2781 public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
2782 throws NumberParseException {
2783 PhoneNumber phoneNumber = new PhoneNumber();
2784 parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
2789 * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
2790 * a parameter to decrease object creation when invoked many times.
2792 public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
2793 PhoneNumber phoneNumber)
2794 throws NumberParseException {
2795 parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
2799 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
2800 * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
2801 * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
2803 * @param text the text to search for phone numbers, null for no text
2804 * @param defaultRegion region that we are expecting the number to be from. This is only used
2805 * if the number being parsed is not written in international format. The
2806 * country_code for the number in this case would be stored as that of
2807 * the default region supplied. May be null if only international
2808 * numbers are expected.
2810 public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
2811 return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
2815 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
2817 * @param text the text to search for phone numbers, null for no text
2818 * @param defaultRegion region that we are expecting the number to be from. This is only used
2819 * if the number being parsed is not written in international format. The
2820 * country_code for the number in this case would be stored as that of
2821 * the default region supplied. May be null if only international
2822 * numbers are expected.
2823 * @param leniency the leniency to use when evaluating candidate phone numbers
2824 * @param maxTries the maximum number of invalid numbers to try before giving up on the
2825 * text. This is to cover degenerate cases where the text has a lot of
2826 * false positives in it. Must be {@code >= 0}.
2828 public Iterable<PhoneNumberMatch> findNumbers(
2829 final CharSequence text, final String defaultRegion, final Leniency leniency,
2830 final long maxTries) {
2832 return new Iterable<PhoneNumberMatch>() {
2833 public Iterator<PhoneNumberMatch> iterator() {
2834 return new PhoneNumberMatcher(
2835 PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
2841 * A helper function to set the values related to leading zeros in a PhoneNumber.
2843 static void setItalianLeadingZerosForPhoneNumber(String nationalNumber, PhoneNumber phoneNumber) {
2844 if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') {
2845 phoneNumber.setItalianLeadingZero(true);
2846 int numberOfLeadingZeros = 1;
2847 // Note that if the national number is all "0"s, the last "0" is not counted as a leading
2849 while (numberOfLeadingZeros < nationalNumber.length() - 1 &&
2850 nationalNumber.charAt(numberOfLeadingZeros) == '0') {
2851 numberOfLeadingZeros++;
2853 if (numberOfLeadingZeros != 1) {
2854 phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros);
2860 * Parses a string and fills up the phoneNumber. This method is the same as the public
2861 * parse() method, with the exception that it allows the default region to be null, for use by
2862 * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
2863 * to be null or unknown ("ZZ").
2865 private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
2866 boolean checkRegion, PhoneNumber phoneNumber)
2867 throws NumberParseException {
2868 if (numberToParse == null) {
2869 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2870 "The phone number supplied was null.");
2871 } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
2872 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2873 "The string supplied was too long to parse.");
2876 StringBuilder nationalNumber = new StringBuilder();
2877 buildNationalNumberForParsing(numberToParse, nationalNumber);
2879 if (!isViablePhoneNumber(nationalNumber.toString())) {
2880 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
2881 "The string supplied did not seem to be a phone number.");
2884 // Check the region supplied is valid, or that the extracted number starts with some sort of +
2885 // sign so the number's region can be determined.
2886 if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
2887 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2888 "Missing or invalid default region.");
2892 phoneNumber.setRawInput(numberToParse);
2894 // Attempt to parse extension first, since it doesn't require region-specific data and we want
2895 // to have the non-normalised number here.
2896 String extension = maybeStripExtension(nationalNumber);
2897 if (extension.length() > 0) {
2898 phoneNumber.setExtension(extension);
2901 PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
2902 // Check to see if the number is given in international format so we know whether this number is
2903 // from the default region or not.
2904 StringBuilder normalizedNationalNumber = new StringBuilder();
2905 int countryCode = 0;
2907 // TODO: This method should really just take in the string buffer that has already
2908 // been created, and just remove the prefix, rather than taking in a string and then
2909 // outputting a string buffer.
2910 countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
2911 normalizedNationalNumber, keepRawInput, phoneNumber);
2912 } catch (NumberParseException e) {
2913 Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
2914 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
2915 matcher.lookingAt()) {
2916 // Strip the plus-char, and try again.
2917 countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
2918 regionMetadata, normalizedNationalNumber,
2919 keepRawInput, phoneNumber);
2920 if (countryCode == 0) {
2921 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2922 "Could not interpret numbers after plus-sign.");
2925 throw new NumberParseException(e.getErrorType(), e.getMessage());
2928 if (countryCode != 0) {
2929 String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
2930 if (!phoneNumberRegion.equals(defaultRegion)) {
2931 // Metadata cannot be null because the country calling code is valid.
2932 regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
2935 // If no extracted country calling code, use the region supplied instead. The national number
2936 // is just the normalized version of the number we were given to parse.
2937 normalize(nationalNumber);
2938 normalizedNationalNumber.append(nationalNumber);
2939 if (defaultRegion != null) {
2940 countryCode = regionMetadata.getCountryCode();
2941 phoneNumber.setCountryCode(countryCode);
2942 } else if (keepRawInput) {
2943 phoneNumber.clearCountryCodeSource();
2946 if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
2947 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2948 "The string supplied is too short to be a phone number.");
2950 if (regionMetadata != null) {
2951 StringBuilder carrierCode = new StringBuilder();
2952 StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
2953 maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
2954 // We require that the NSN remaining after stripping the national prefix and carrier code be
2955 // of a possible length for the region. Otherwise, we don't do the stripping, since the
2956 // original number could be a valid short number.
2957 if (!isShorterThanPossibleNormalNumber(regionMetadata, potentialNationalNumber.toString())) {
2958 normalizedNationalNumber = potentialNationalNumber;
2960 phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
2964 int lengthOfNationalNumber = normalizedNationalNumber.length();
2965 if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
2966 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2967 "The string supplied is too short to be a phone number.");
2969 if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
2970 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2971 "The string supplied is too long to be a phone number.");
2973 setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber.toString(), phoneNumber);
2974 phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
2978 * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
2979 * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
2981 private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
2982 int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
2983 if (indexOfPhoneContext > 0) {
2984 int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
2985 // If the phone context contains a phone number prefix, we need to capture it, whereas domains
2987 if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
2988 // Additional parameters might follow the phone context. If so, we will remove them here
2989 // because the parameters after phone context are not important for parsing the
2991 int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
2992 if (phoneContextEnd > 0) {
2993 nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
2995 nationalNumber.append(numberToParse.substring(phoneContextStart));
2999 // Now append everything between the "tel:" prefix and the phone-context. This should include
3000 // the national number, an optional extension or isdn-subaddress component. Note we also
3001 // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
3002 // In that case, we append everything from the beginning.
3003 int indexOfRfc3966Prefix = numberToParse.indexOf(RFC3966_PREFIX);
3004 int indexOfNationalNumber = (indexOfRfc3966Prefix >= 0) ?
3005 indexOfRfc3966Prefix + RFC3966_PREFIX.length() : 0;
3006 nationalNumber.append(numberToParse.substring(indexOfNationalNumber, indexOfPhoneContext));
3008 // Extract a possible number from the string passed in (this strips leading characters that
3009 // could not be the start of a phone number.)
3010 nationalNumber.append(extractPossibleNumber(numberToParse));
3013 // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
3014 // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
3015 int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
3016 if (indexOfIsdn > 0) {
3017 nationalNumber.delete(indexOfIsdn, nationalNumber.length());
3019 // If both phone context and isdn-subaddress are absent but other parameters are present, the
3020 // parameters are left in nationalNumber. This is because we are concerned about deleting
3021 // content from a potential number string when there is no strong evidence that the number is
3022 // actually written in RFC3966.
3026 * Takes two phone numbers and compares them for equality.
3028 * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
3029 * and any extension present are the same.
3030 * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
3032 * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
3033 * the same, and one NSN could be a shorter version of the other number. This includes the case
3034 * where one has an extension specified, and the other does not.
3035 * Returns NO_MATCH otherwise.
3036 * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
3037 * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
3039 * @param firstNumberIn first number to compare
3040 * @param secondNumberIn second number to compare
3042 * @return NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
3043 * of the two numbers, described in the method definition.
3045 public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
3046 // Make copies of the phone number so that the numbers passed in are not edited.
3047 PhoneNumber firstNumber = new PhoneNumber();
3048 firstNumber.mergeFrom(firstNumberIn);
3049 PhoneNumber secondNumber = new PhoneNumber();
3050 secondNumber.mergeFrom(secondNumberIn);
3051 // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
3052 // empty-string extensions so that we can use the proto-buffer equality method.
3053 firstNumber.clearRawInput();
3054 firstNumber.clearCountryCodeSource();
3055 firstNumber.clearPreferredDomesticCarrierCode();
3056 secondNumber.clearRawInput();
3057 secondNumber.clearCountryCodeSource();
3058 secondNumber.clearPreferredDomesticCarrierCode();
3059 if (firstNumber.hasExtension() &&
3060 firstNumber.getExtension().length() == 0) {
3061 firstNumber.clearExtension();
3063 if (secondNumber.hasExtension() &&
3064 secondNumber.getExtension().length() == 0) {
3065 secondNumber.clearExtension();
3067 // Early exit if both had extensions and these are different.
3068 if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
3069 !firstNumber.getExtension().equals(secondNumber.getExtension())) {
3070 return MatchType.NO_MATCH;
3072 int firstNumberCountryCode = firstNumber.getCountryCode();
3073 int secondNumberCountryCode = secondNumber.getCountryCode();
3074 // Both had country_code specified.
3075 if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
3076 if (firstNumber.exactlySameAs(secondNumber)) {
3077 return MatchType.EXACT_MATCH;
3078 } else if (firstNumberCountryCode == secondNumberCountryCode &&
3079 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3080 // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
3081 // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
3082 // shorter variant of the other.
3083 return MatchType.SHORT_NSN_MATCH;
3085 // This is not a match.
3086 return MatchType.NO_MATCH;
3088 // Checks cases where one or both country_code fields were not specified. To make equality
3089 // checks easier, we first set the country_code fields to be equal.
3090 firstNumber.setCountryCode(secondNumberCountryCode);
3091 // If all else was the same, then this is an NSN_MATCH.
3092 if (firstNumber.exactlySameAs(secondNumber)) {
3093 return MatchType.NSN_MATCH;
3095 if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
3096 return MatchType.SHORT_NSN_MATCH;
3098 return MatchType.NO_MATCH;
3101 // Returns true when one national number is the suffix of the other or both are the same.
3102 private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
3103 PhoneNumber secondNumber) {
3104 String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
3105 String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
3106 // Note that endsWith returns true if the numbers are equal.
3107 return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
3108 secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
3112 * Takes two phone numbers as strings and compares them for equality. This is a convenience
3113 * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3115 * @param firstNumber first number to compare. Can contain formatting, and can have country
3116 * calling code specified with + at the start.
3117 * @param secondNumber second number to compare. Can contain formatting, and can have country
3118 * calling code specified with + at the start.
3119 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3120 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3122 public MatchType isNumberMatch(String firstNumber, String secondNumber) {
3124 PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
3125 return isNumberMatch(firstNumberAsProto, secondNumber);
3126 } catch (NumberParseException e) {
3127 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3129 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3130 return isNumberMatch(secondNumberAsProto, firstNumber);
3131 } catch (NumberParseException e2) {
3132 if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3134 PhoneNumber firstNumberProto = new PhoneNumber();
3135 PhoneNumber secondNumberProto = new PhoneNumber();
3136 parseHelper(firstNumber, null, false, false, firstNumberProto);
3137 parseHelper(secondNumber, null, false, false, secondNumberProto);
3138 return isNumberMatch(firstNumberProto, secondNumberProto);
3139 } catch (NumberParseException e3) {
3140 // Fall through and return MatchType.NOT_A_NUMBER.
3146 // One or more of the phone numbers we are trying to match is not a viable phone number.
3147 return MatchType.NOT_A_NUMBER;
3151 * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
3152 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
3154 * @param firstNumber first number to compare in proto buffer format.
3155 * @param secondNumber second number to compare. Can contain formatting, and can have country
3156 * calling code specified with + at the start.
3157 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
3158 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
3160 public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
3161 // First see if the second number has an implicit country calling code, by attempting to parse
3164 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
3165 return isNumberMatch(firstNumber, secondNumberAsProto);
3166 } catch (NumberParseException e) {
3167 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3168 // The second number has no country calling code. EXACT_MATCH is no longer possible.
3169 // We parse it as if the region was the same as that for the first number, and if
3170 // EXACT_MATCH is returned, we replace this with NSN_MATCH.
3171 String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
3173 if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
3174 PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
3175 MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
3176 if (match == MatchType.EXACT_MATCH) {
3177 return MatchType.NSN_MATCH;
3181 // If the first number didn't have a valid country calling code, then we parse the
3182 // second number without one as well.
3183 PhoneNumber secondNumberProto = new PhoneNumber();
3184 parseHelper(secondNumber, null, false, false, secondNumberProto);
3185 return isNumberMatch(firstNumber, secondNumberProto);
3187 } catch (NumberParseException e2) {
3188 // Fall-through to return NOT_A_NUMBER.
3192 // One or more of the phone numbers we are trying to match is not a viable phone number.
3193 return MatchType.NOT_A_NUMBER;
3197 * Returns true if the number can be dialled from outside the region, or unknown. If the number
3198 * can only be dialled from within the region, returns false. Does not check the number is a valid
3199 * number. Note that, at the moment, this method does not handle short numbers.
3200 * TODO: Make this method public when we have enough metadata to make it worthwhile.
3202 * @param number the phone-number for which we want to know whether it is diallable from
3203 * outside the region
3205 // @VisibleForTesting
3206 boolean canBeInternationallyDialled(PhoneNumber number) {
3207 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3208 if (metadata == null) {
3209 // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3210 // internationally diallable, and will be caught here.
3213 String nationalSignificantNumber = getNationalSignificantNumber(number);
3214 return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
3218 * Returns true if the supplied region supports mobile number portability. Returns false for
3219 * invalid, unknown or regions that don't support mobile number portability.
3221 * @param regionCode the region for which we want to know whether it supports mobile number
3222 * portability or not.
3224 public boolean isMobileNumberPortableRegion(String regionCode) {
3225 PhoneMetadata metadata = getMetadataForRegion(regionCode);
3226 if (metadata == null) {
3227 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
3230 return metadata.isMobileNumberPortableRegion();