1 // Copyright (C) 2009 The Libphonenumber Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // Author: Shaopeng Jia
16 // Open-sourced by: Philippe Liard
18 #include "phonenumbers/phonenumberutil.h"
31 #include <google/protobuf/message_lite.h>
32 #include <unicode/uchar.h>
33 #include <unicode/utf8.h>
35 #include "phonenumbers/asyoutypeformatter.h"
36 #include "phonenumbers/base/basictypes.h"
37 #include "phonenumbers/base/logging.h"
38 #include "phonenumbers/base/memory/singleton.h"
39 #include "phonenumbers/default_logger.h"
40 #include "phonenumbers/encoding_utils.h"
41 #include "phonenumbers/metadata.h"
42 #include "phonenumbers/normalize_utf8.h"
43 #include "phonenumbers/phonemetadata.pb.h"
44 #include "phonenumbers/phonenumber.h"
45 #include "phonenumbers/phonenumber.pb.h"
46 #include "phonenumbers/regexp_adapter.h"
47 #include "phonenumbers/regexp_cache.h"
48 #include "phonenumbers/regexp_factory.h"
49 #include "phonenumbers/region_code.h"
50 #include "phonenumbers/stl_util.h"
51 #include "phonenumbers/stringutil.h"
52 #include "phonenumbers/utf/unicodetext.h"
53 #include "phonenumbers/utf/utf.h"
56 namespace phonenumbers {
63 using std::stringstream;
65 using google::protobuf::RepeatedPtrField;
68 const char PhoneNumberUtil::kPlusChars[] = "+\xEF\xBC\x8B"; /* "++" */
69 // To find out the unicode code-point of the characters below in vim, highlight
70 // the character and type 'ga'. Note that the - is used to express ranges of
71 // full-width punctuation below, as well as being present in the expression
72 // itself. In emacs, you can use M-x unicode-what to query information about the
75 const char PhoneNumberUtil::kValidPunctuation[] =
76 /* "-x‐-―−ー--/ <U+200B><U+2060> ()()[].\\[\\]/~⁓∼" */
77 "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC"
78 "\x8F \xC2\xA0\xC2\xAD\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88"
79 "\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC";
82 const char PhoneNumberUtil::kCaptureUpToSecondNumberStart[] = "(.*)[\\\\/] *x";
85 const char PhoneNumberUtil::kRegionCodeForNonGeoEntity[] = "001";
89 // The prefix that needs to be inserted in front of a Colombian landline
90 // number when dialed from a mobile phone in Colombia.
91 const char kColombiaMobileToFixedLinePrefix[] = "3";
93 // The kPlusSign signifies the international prefix.
94 const char kPlusSign[] = "+";
96 const char kStarSign[] = "*";
98 const char kRfc3966ExtnPrefix[] = ";ext=";
99 const char kRfc3966Prefix[] = "tel:";
100 const char kRfc3966PhoneContext[] = ";phone-context=";
101 const char kRfc3966IsdnSubaddress[] = ";isub=";
103 const char kDigits[] = "\\p{Nd}";
104 // We accept alpha characters in phone numbers, ASCII only. We store lower-case
105 // here only since our regular expressions are case-insensitive.
106 const char kValidAlpha[] = "a-z";
108 // Default extension prefix to use when formatting. This will be put in front of
109 // any extension component of the number, after the main national number is
110 // formatted. For example, if you wish the default extension formatting to be "
111 // extn: 3456", then you should specify " extn: " here as the default extension
112 // prefix. This can be overridden by region-specific preferences.
113 const char kDefaultExtnPrefix[] = " ext. ";
115 // One-character symbols that can be used to indicate an extension.
116 const char kSingleExtnSymbolsForMatching[] =
117 "x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E";
119 bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) {
120 if (!metadata->ParseFromArray(metadata_get(), metadata_size())) {
121 cerr << "Could not parse binary data." << endl;
127 // Returns a pointer to the description inside the metadata of the appropriate
129 const PhoneNumberDesc* GetNumberDescByType(
130 const PhoneMetadata& metadata,
131 PhoneNumberUtil::PhoneNumberType type) {
133 case PhoneNumberUtil::PREMIUM_RATE:
134 return &metadata.premium_rate();
135 case PhoneNumberUtil::TOLL_FREE:
136 return &metadata.toll_free();
137 case PhoneNumberUtil::MOBILE:
138 return &metadata.mobile();
139 case PhoneNumberUtil::FIXED_LINE:
140 case PhoneNumberUtil::FIXED_LINE_OR_MOBILE:
141 return &metadata.fixed_line();
142 case PhoneNumberUtil::SHARED_COST:
143 return &metadata.shared_cost();
144 case PhoneNumberUtil::VOIP:
145 return &metadata.voip();
146 case PhoneNumberUtil::PERSONAL_NUMBER:
147 return &metadata.personal_number();
148 case PhoneNumberUtil::PAGER:
149 return &metadata.pager();
150 case PhoneNumberUtil::UAN:
151 return &metadata.uan();
152 case PhoneNumberUtil::VOICEMAIL:
153 return &metadata.voicemail();
155 return &metadata.general_desc();
159 // A helper function that is used by Format and FormatByPattern.
160 void PrefixNumberWithCountryCallingCode(
161 int country_calling_code,
162 PhoneNumberUtil::PhoneNumberFormat number_format,
163 string* formatted_number) {
164 switch (number_format) {
165 case PhoneNumberUtil::E164:
166 formatted_number->insert(0, StrCat(kPlusSign, country_calling_code));
168 case PhoneNumberUtil::INTERNATIONAL:
169 formatted_number->insert(0, StrCat(kPlusSign, country_calling_code, " "));
171 case PhoneNumberUtil::RFC3966:
172 formatted_number->insert(0, StrCat(kRfc3966Prefix, kPlusSign,
173 country_calling_code, "-"));
175 case PhoneNumberUtil::NATIONAL:
182 // Returns true when one national number is the suffix of the other or both are
184 bool IsNationalNumberSuffixOfTheOther(const PhoneNumber& first_number,
185 const PhoneNumber& second_number) {
186 const string& first_number_national_number =
187 SimpleItoa(static_cast<uint64>(first_number.national_number()));
188 const string& second_number_national_number =
189 SimpleItoa(static_cast<uint64>(second_number.national_number()));
190 // Note that HasSuffixString returns true if the numbers are equal.
191 return HasSuffixString(first_number_national_number,
192 second_number_national_number) ||
193 HasSuffixString(second_number_national_number,
194 first_number_national_number);
197 bool IsNumberMatchingDesc(const string& national_number,
198 const PhoneNumberDesc& number_desc,
199 RegExpCache* regexp_cache) {
200 return regexp_cache->GetRegExp(number_desc.possible_number_pattern())
201 .FullMatch(national_number) &&
202 regexp_cache->GetRegExp(number_desc.national_number_pattern())
203 .FullMatch(national_number);
206 PhoneNumberUtil::PhoneNumberType GetNumberTypeHelper(
207 const string& national_number, const PhoneMetadata& metadata,
208 RegExpCache* regexp_cache) {
209 const PhoneNumberDesc& general_desc = metadata.general_desc();
210 if (!general_desc.has_national_number_pattern() ||
211 !IsNumberMatchingDesc(national_number, general_desc, regexp_cache)) {
212 VLOG(4) << "Number type unknown - doesn't match general national number"
214 return PhoneNumberUtil::UNKNOWN;
216 if (IsNumberMatchingDesc(national_number, metadata.premium_rate(),
218 VLOG(4) << "Number is a premium number.";
219 return PhoneNumberUtil::PREMIUM_RATE;
221 if (IsNumberMatchingDesc(national_number, metadata.toll_free(),
223 VLOG(4) << "Number is a toll-free number.";
224 return PhoneNumberUtil::TOLL_FREE;
226 if (IsNumberMatchingDesc(national_number, metadata.shared_cost(),
228 VLOG(4) << "Number is a shared cost number.";
229 return PhoneNumberUtil::SHARED_COST;
231 if (IsNumberMatchingDesc(national_number, metadata.voip(), regexp_cache)) {
232 VLOG(4) << "Number is a VOIP (Voice over IP) number.";
233 return PhoneNumberUtil::VOIP;
235 if (IsNumberMatchingDesc(national_number, metadata.personal_number(),
237 VLOG(4) << "Number is a personal number.";
238 return PhoneNumberUtil::PERSONAL_NUMBER;
240 if (IsNumberMatchingDesc(national_number, metadata.pager(), regexp_cache)) {
241 VLOG(4) << "Number is a pager number.";
242 return PhoneNumberUtil::PAGER;
244 if (IsNumberMatchingDesc(national_number, metadata.uan(), regexp_cache)) {
245 VLOG(4) << "Number is a UAN.";
246 return PhoneNumberUtil::UAN;
248 if (IsNumberMatchingDesc(national_number, metadata.voicemail(),
250 VLOG(4) << "Number is a voicemail number.";
251 return PhoneNumberUtil::VOICEMAIL;
255 IsNumberMatchingDesc(national_number, metadata.fixed_line(),
258 if (metadata.same_mobile_and_fixed_line_pattern()) {
259 VLOG(4) << "Fixed-line and mobile patterns equal, number is fixed-line"
261 return PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
262 } else if (IsNumberMatchingDesc(national_number, metadata.mobile(),
264 VLOG(4) << "Fixed-line and mobile patterns differ, but number is "
265 << "still fixed-line or mobile";
266 return PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
268 VLOG(4) << "Number is a fixed line number.";
269 return PhoneNumberUtil::FIXED_LINE;
271 // Otherwise, test to see if the number is mobile. Only do this if certain
272 // that the patterns for mobile and fixed line aren't the same.
273 if (!metadata.same_mobile_and_fixed_line_pattern() &&
274 IsNumberMatchingDesc(national_number, metadata.mobile(), regexp_cache)) {
275 VLOG(4) << "Number is a mobile number.";
276 return PhoneNumberUtil::MOBILE;
278 VLOG(4) << "Number type unknown - doesn\'t match any specific number type"
280 return PhoneNumberUtil::UNKNOWN;
283 char32 ToUnicodeCodepoint(const char* unicode_char) {
285 EncodingUtils::DecodeUTF8Char(unicode_char, &codepoint);
289 // Helper initialiser method to create the regular-expression pattern to match
290 // extensions, allowing the one-codepoint extension symbols provided by
291 // single_extn_symbols.
292 // Note that there are currently three capturing groups for the extension itself
293 // - if this number is changed, MaybeStripExtension needs to be updated.
294 string CreateExtnPattern(const string& single_extn_symbols) {
295 static const string capturing_extn_digits = StrCat("([", kDigits, "]{1,7})");
296 // The first regular expression covers RFC 3966 format, where the extension is
297 // added using ";ext=". The second more generic one starts with optional white
298 // space and ends with an optional full stop (.), followed by zero or more
299 // spaces/tabs and then the numbers themselves. The third one covers the
300 // special case of American numbers where the extension is written with a hash
301 // at the end, such as "- 503#".
302 // Note that the only capturing groups should be around the digits that you
303 // want to capture as part of the extension, or else parsing will fail!
304 // Canonical-equivalence doesn't seem to be an option with RE2, so we allow
305 // two options for representing the ó - the character itself, and one in the
306 // unicode decomposed form with the combining acute accent.
308 kRfc3966ExtnPrefix, capturing_extn_digits, "|"
309 /* "[ \\t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|single_extn_symbols|"
311 "[:\\..]?[ \\t,-]*", capturing_extn_digits, "#?|" */
312 "[ \xC2\xA0\\t,]*(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|"
313 "(?:\xEF\xBD\x85)?\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|"
314 "[", single_extn_symbols, "]|int|"
315 "\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94|anexo)"
316 "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*", capturing_extn_digits,
317 "#?|[- ]+([", kDigits, "]{1,5})#"));
320 // Normalizes a string of characters representing a phone number by replacing
321 // all characters found in the accompanying map with the values therein, and
322 // stripping all other characters if remove_non_matches is true.
324 // number - a pointer to a string of characters representing a phone number to
326 // normalization_replacements - a mapping of characters to what they should be
327 // replaced by in the normalized version of the phone number
328 // remove_non_matches - indicates whether characters that are not able to be
329 // replaced should be stripped from the number. If this is false, they will be
330 // left unchanged in the number.
331 void NormalizeHelper(const map<char32, char>& normalization_replacements,
332 bool remove_non_matches,
335 UnicodeText number_as_unicode;
336 number_as_unicode.PointToUTF8(number->data(), number->size());
337 string normalized_number;
338 char unicode_char[5];
339 for (UnicodeText::const_iterator it = number_as_unicode.begin();
340 it != number_as_unicode.end();
342 map<char32, char>::const_iterator found_glyph_pair =
343 normalization_replacements.find(*it);
344 if (found_glyph_pair != normalization_replacements.end()) {
345 normalized_number.push_back(found_glyph_pair->second);
346 } else if (!remove_non_matches) {
347 // Find out how long this unicode char is so we can append it all.
348 int char_len = it.get_utf8(unicode_char);
349 normalized_number.append(unicode_char, char_len);
351 // If neither of the above are true, we remove this character.
353 number->assign(normalized_number);
356 PhoneNumberUtil::ValidationResult TestNumberLengthAgainstPattern(
357 const RegExp& number_pattern, const string& number) {
358 string extracted_number;
359 if (number_pattern.FullMatch(number, &extracted_number)) {
360 return PhoneNumberUtil::IS_POSSIBLE;
362 if (number_pattern.PartialMatch(number, &extracted_number)) {
363 return PhoneNumberUtil::TOO_LONG;
365 return PhoneNumberUtil::TOO_SHORT;
371 void PhoneNumberUtil::SetLogger(Logger* logger) {
372 logger_.reset(logger);
373 Logger::set_logger_impl(logger_.get());
376 class PhoneNumberRegExpsAndMappings {
378 void InitializeMapsAndSets() {
379 diallable_char_mappings_.insert(make_pair('+', '+'));
380 diallable_char_mappings_.insert(make_pair('*', '*'));
381 // Here we insert all punctuation symbols that we wish to respect when
382 // formatting alpha numbers, as they show the intended number groupings.
383 all_plus_number_grouping_symbols_.insert(
384 make_pair(ToUnicodeCodepoint("-"), '-'));
385 all_plus_number_grouping_symbols_.insert(
386 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8D" /* "-" */), '-'));
387 all_plus_number_grouping_symbols_.insert(
388 make_pair(ToUnicodeCodepoint("\xE2\x80\x90" /* "‐" */), '-'));
389 all_plus_number_grouping_symbols_.insert(
390 make_pair(ToUnicodeCodepoint("\xE2\x80\x91" /* "‑" */), '-'));
391 all_plus_number_grouping_symbols_.insert(
392 make_pair(ToUnicodeCodepoint("\xE2\x80\x92" /* "‒" */), '-'));
393 all_plus_number_grouping_symbols_.insert(
394 make_pair(ToUnicodeCodepoint("\xE2\x80\x93" /* "–" */), '-'));
395 all_plus_number_grouping_symbols_.insert(
396 make_pair(ToUnicodeCodepoint("\xE2\x80\x94" /* "—" */), '-'));
397 all_plus_number_grouping_symbols_.insert(
398 make_pair(ToUnicodeCodepoint("\xE2\x80\x95" /* "―" */), '-'));
399 all_plus_number_grouping_symbols_.insert(
400 make_pair(ToUnicodeCodepoint("\xE2\x88\x92" /* "−" */), '-'));
401 all_plus_number_grouping_symbols_.insert(
402 make_pair(ToUnicodeCodepoint("/"), '/'));
403 all_plus_number_grouping_symbols_.insert(
404 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8F" /* "/" */), '/'));
405 all_plus_number_grouping_symbols_.insert(
406 make_pair(ToUnicodeCodepoint(" "), ' '));
407 all_plus_number_grouping_symbols_.insert(
408 make_pair(ToUnicodeCodepoint("\xE3\x80\x80" /* " " */), ' '));
409 all_plus_number_grouping_symbols_.insert(
410 make_pair(ToUnicodeCodepoint("\xE2\x81\xA0"), ' '));
411 all_plus_number_grouping_symbols_.insert(
412 make_pair(ToUnicodeCodepoint("."), '.'));
413 all_plus_number_grouping_symbols_.insert(
414 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8E" /* "." */), '.'));
415 // Only the upper-case letters are added here - the lower-case versions are
416 // added programmatically.
417 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("A"), '2'));
418 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("B"), '2'));
419 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("C"), '2'));
420 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("D"), '3'));
421 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("E"), '3'));
422 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("F"), '3'));
423 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("G"), '4'));
424 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("H"), '4'));
425 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("I"), '4'));
426 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("J"), '5'));
427 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("K"), '5'));
428 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("L"), '5'));
429 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("M"), '6'));
430 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("N"), '6'));
431 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("O"), '6'));
432 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("P"), '7'));
433 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Q"), '7'));
434 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("R"), '7'));
435 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("S"), '7'));
436 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("T"), '8'));
437 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("U"), '8'));
438 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("V"), '8'));
439 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("W"), '9'));
440 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("X"), '9'));
441 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Y"), '9'));
442 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Z"), '9'));
443 map<char32, char> lower_case_mappings;
444 map<char32, char> alpha_letters;
445 for (map<char32, char>::const_iterator it = alpha_mappings_.begin();
446 it != alpha_mappings_.end();
448 // Convert all the upper-case ASCII letters to lower-case.
449 if (it->first < 128) {
450 char letter_as_upper = static_cast<char>(it->first);
451 char32 letter_as_lower = static_cast<char32>(tolower(letter_as_upper));
452 lower_case_mappings.insert(make_pair(letter_as_lower, it->second));
453 // Add the letters in both variants to the alpha_letters map. This just
454 // pairs each letter with its upper-case representation so that it can
455 // be retained when normalising alpha numbers.
456 alpha_letters.insert(make_pair(letter_as_lower, letter_as_upper));
457 alpha_letters.insert(make_pair(it->first, letter_as_upper));
460 // In the Java version we don't insert the lower-case mappings in the map,
461 // because we convert to upper case on the fly. Doing this here would
462 // involve pulling in all of ICU, which we don't want to do if we don't have
464 alpha_mappings_.insert(lower_case_mappings.begin(),
465 lower_case_mappings.end());
466 alpha_phone_mappings_.insert(alpha_mappings_.begin(),
467 alpha_mappings_.end());
468 all_plus_number_grouping_symbols_.insert(alpha_letters.begin(),
469 alpha_letters.end());
470 // Add the ASCII digits so that they don't get deleted by NormalizeHelper().
471 for (char c = '0'; c <= '9'; ++c) {
472 diallable_char_mappings_.insert(make_pair(c, c));
473 alpha_phone_mappings_.insert(make_pair(c, c));
474 all_plus_number_grouping_symbols_.insert(make_pair(c, c));
478 // Small string helpers since StrCat has a maximum number of arguments. These
479 // are both used to build valid_phone_number_.
480 const string punctuation_and_star_sign_;
481 const string min_length_phone_number_pattern_;
483 // Regular expression of viable phone numbers. This is location independent.
484 // Checks we have at least three leading digits, and only valid punctuation,
485 // alpha characters and digits in the phone number. Does not include extension
486 // data. The symbol 'x' is allowed here as valid punctuation since it is often
487 // used as a placeholder for carrier codes, for example in Brazilian phone
488 // numbers. We also allow multiple plus-signs at the start.
489 // Corresponds to the following:
490 // [digits]{minLengthNsn}|
491 // plus_sign*(([punctuation]|[star])*[digits]){3,}
492 // ([punctuation]|[star]|[digits]|[alpha])*
494 // The first reg-ex is to allow short numbers (two digits long) to be parsed
495 // if they are entered as "15" etc, but only if there is no punctuation in
496 // them. The second expression restricts the number of digits to three or
497 // more, but then allows them to be in international form, and to have
498 // alpha-characters and punctuation.
499 const string valid_phone_number_;
501 // Regexp of all possible ways to write extensions, for use when parsing. This
502 // will be run as a case-insensitive regexp match. Wide character versions are
503 // also provided after each ASCII version.
504 // For parsing, we are slightly more lenient in our interpretation than for
505 // matching. Here we allow a "comma" as a possible extension indicator. When
506 // matching, this is hardly ever used to indicate this.
507 const string extn_patterns_for_parsing_;
510 scoped_ptr<const AbstractRegExpFactory> regexp_factory_;
511 scoped_ptr<RegExpCache> regexp_cache_;
513 // A map that contains characters that are essential when dialling. That means
514 // any of the characters in this map must not be removed from a number when
515 // dialing, otherwise the call will not reach the intended destination.
516 map<char32, char> diallable_char_mappings_;
517 // These mappings map a character (key) to a specific digit that should
518 // replace it for normalization purposes.
519 map<char32, char> alpha_mappings_;
520 // For performance reasons, store a map of combining alpha_mappings with ASCII
522 map<char32, char> alpha_phone_mappings_;
524 // Separate map of all symbols that we wish to retain when formatting alpha
525 // numbers. This includes digits, ascii letters and number grouping symbols
526 // such as "-" and " ".
527 map<char32, char> all_plus_number_grouping_symbols_;
529 // Pattern that makes it easy to distinguish whether a region has a unique
530 // international dialing prefix or not. If a region has a unique international
531 // prefix (e.g. 011 in USA), it will be represented as a string that contains
532 // a sequence of ASCII digits. If there are multiple available international
533 // prefixes in a region, they will be represented as a regex string that
534 // always contains character(s) other than ASCII digits.
535 // Note this regex also includes tilde, which signals waiting for the tone.
536 scoped_ptr<const RegExp> unique_international_prefix_;
538 scoped_ptr<const RegExp> digits_pattern_;
539 scoped_ptr<const RegExp> capturing_digit_pattern_;
540 scoped_ptr<const RegExp> capturing_ascii_digits_pattern_;
542 // Regular expression of acceptable characters that may start a phone number
543 // for the purposes of parsing. This allows us to strip away meaningless
544 // prefixes to phone numbers that may be mistakenly given to us. This consists
545 // of digits, the plus symbol and arabic-indic digits. This does not contain
546 // alpha characters, although they may be used later in the number. It also
547 // does not include other punctuation, as this will be stripped later during
548 // parsing and is of no information value when parsing a number. The string
549 // starting with this valid character is captured.
550 // This corresponds to VALID_START_CHAR in the java version.
551 scoped_ptr<const RegExp> valid_start_char_pattern_;
553 // Regular expression of valid characters before a marker that might indicate
555 scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_;
557 // Regular expression of trailing characters that we want to remove. We remove
558 // all characters that are not alpha or numerical characters. The hash
559 // character is retained here, as it may signify the previous block was an
560 // extension. Note the capturing block at the start to capture the rest of the
561 // number if this was a match.
562 // This corresponds to UNWANTED_END_CHAR_PATTERN in the java version.
563 scoped_ptr<const RegExp> unwanted_end_char_pattern_;
565 // Regular expression of groups of valid punctuation characters.
566 scoped_ptr<const RegExp> separator_pattern_;
568 // Regexp of all possible ways to write extensions, for use when finding phone
569 // numbers in text. This will be run as a case-insensitive regexp match. Wide
570 // character versions are also provided after each ASCII version.
571 const string extn_patterns_for_matching_;
573 // Regexp of all known extension prefixes used by different regions followed
574 // by 1 or more valid digits, for use when parsing.
575 scoped_ptr<const RegExp> extn_pattern_;
577 // We append optionally the extension pattern to the end here, as a valid
578 // phone number may have an extension prefix appended, followed by 1 or more
580 scoped_ptr<const RegExp> valid_phone_number_pattern_;
582 // We use this pattern to check if the phone number has at least three letters
583 // in it - if so, then we treat it as a number where some phone-number digits
584 // are represented by letters.
585 scoped_ptr<const RegExp> valid_alpha_phone_pattern_;
587 scoped_ptr<const RegExp> first_group_capturing_pattern_;
589 scoped_ptr<const RegExp> carrier_code_pattern_;
591 scoped_ptr<const RegExp> plus_chars_pattern_;
593 PhoneNumberRegExpsAndMappings()
594 : punctuation_and_star_sign_(StrCat(PhoneNumberUtil::kValidPunctuation,
596 min_length_phone_number_pattern_(
597 StrCat(kDigits, "{", PhoneNumberUtil::kMinLengthForNsn, "}")),
599 StrCat(min_length_phone_number_pattern_, "|[",
600 PhoneNumberUtil::kPlusChars, "]*(?:[",
601 punctuation_and_star_sign_, "]*",
602 kDigits, "){3,}[", kValidAlpha,
603 punctuation_and_star_sign_, kDigits,
605 extn_patterns_for_parsing_(
606 CreateExtnPattern(StrCat(",", kSingleExtnSymbolsForMatching))),
607 regexp_factory_(new RegExpFactory()),
608 regexp_cache_(new RegExpCache(*regexp_factory_.get(), 128)),
609 diallable_char_mappings_(),
611 alpha_phone_mappings_(),
612 all_plus_number_grouping_symbols_(),
613 unique_international_prefix_(regexp_factory_->CreateRegExp(
614 /* "[\\d]+(?:[~⁓∼~][\\d]+)?" */
615 "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?")),
617 regexp_factory_->CreateRegExp(StrCat("[", kDigits, "]*"))),
618 capturing_digit_pattern_(
619 regexp_factory_->CreateRegExp(StrCat("([", kDigits, "])"))),
620 capturing_ascii_digits_pattern_(
621 regexp_factory_->CreateRegExp("(\\d+)")),
622 valid_start_char_pattern_(regexp_factory_->CreateRegExp(
623 StrCat("[", PhoneNumberUtil::kPlusChars, kDigits, "]"))),
624 capture_up_to_second_number_start_pattern_(
625 regexp_factory_->CreateRegExp(
626 PhoneNumberUtil::kCaptureUpToSecondNumberStart)),
627 unwanted_end_char_pattern_(
628 regexp_factory_->CreateRegExp("[^\\p{N}\\p{L}#]")),
630 regexp_factory_->CreateRegExp(
631 StrCat("[", PhoneNumberUtil::kValidPunctuation, "]+"))),
632 extn_patterns_for_matching_(
633 CreateExtnPattern(kSingleExtnSymbolsForMatching)),
634 extn_pattern_(regexp_factory_->CreateRegExp(
635 StrCat("(?i)(?:", extn_patterns_for_parsing_, ")$"))),
636 valid_phone_number_pattern_(regexp_factory_->CreateRegExp(
637 StrCat("(?i)", valid_phone_number_,
638 "(?:", extn_patterns_for_parsing_, ")?"))),
639 valid_alpha_phone_pattern_(regexp_factory_->CreateRegExp(
640 StrCat("(?i)(?:.*?[", kValidAlpha, "]){3}"))),
641 // The first_group_capturing_pattern was originally set to $1 but there
642 // are some countries for which the first group is not used in the
643 // national pattern (e.g. Argentina) so the $1 group does not match
644 // correctly. Therefore, we use \d, so that the first group actually
645 // used in the pattern will be matched.
646 first_group_capturing_pattern_(
647 regexp_factory_->CreateRegExp("(\\$\\d)")),
648 carrier_code_pattern_(regexp_factory_->CreateRegExp("\\$CC")),
650 regexp_factory_->CreateRegExp(
651 StrCat("[", PhoneNumberUtil::kPlusChars, "]+"))) {
652 InitializeMapsAndSets();
656 DISALLOW_COPY_AND_ASSIGN(PhoneNumberRegExpsAndMappings);
659 // Private constructor. Also takes care of initialisation.
660 PhoneNumberUtil::PhoneNumberUtil()
661 : logger_(Logger::set_logger_impl(new NullLogger())),
662 reg_exps_(new PhoneNumberRegExpsAndMappings),
663 country_calling_code_to_region_code_map_(new vector<IntRegionsPair>()),
664 nanpa_regions_(new set<string>()),
665 region_to_metadata_map_(new map<string, PhoneMetadata>()),
666 country_code_to_non_geographical_metadata_map_(
667 new map<int, PhoneMetadata>) {
668 Logger::set_logger_impl(logger_.get());
669 // TODO: Update the java version to put the contents of the init
670 // method inside the constructor as well to keep both in sync.
671 PhoneMetadataCollection metadata_collection;
672 if (!LoadCompiledInMetadata(&metadata_collection)) {
673 LOG(DFATAL) << "Could not parse compiled-in metadata.";
676 // Storing data in a temporary map to make it easier to find other regions
677 // that share a country calling code when inserting data.
678 map<int, list<string>* > country_calling_code_to_region_map;
679 for (RepeatedPtrField<PhoneMetadata>::const_iterator it =
680 metadata_collection.metadata().begin();
681 it != metadata_collection.metadata().end();
683 const string& region_code = it->id();
684 if (region_code == RegionCode::GetUnknown()) {
688 int country_calling_code = it->country_code();
689 if (kRegionCodeForNonGeoEntity == region_code) {
690 country_code_to_non_geographical_metadata_map_->insert(
691 make_pair(country_calling_code, *it));
693 region_to_metadata_map_->insert(make_pair(region_code, *it));
695 map<int, list<string>* >::iterator calling_code_in_map =
696 country_calling_code_to_region_map.find(country_calling_code);
697 if (calling_code_in_map != country_calling_code_to_region_map.end()) {
698 if (it->main_country_for_code()) {
699 calling_code_in_map->second->push_front(region_code);
701 calling_code_in_map->second->push_back(region_code);
704 // For most country calling codes, there will be only one region code.
705 list<string>* list_with_region_code = new list<string>();
706 list_with_region_code->push_back(region_code);
707 country_calling_code_to_region_map.insert(
708 make_pair(country_calling_code, list_with_region_code));
710 if (country_calling_code == kNanpaCountryCode) {
711 nanpa_regions_->insert(region_code);
715 country_calling_code_to_region_code_map_->insert(
716 country_calling_code_to_region_code_map_->begin(),
717 country_calling_code_to_region_map.begin(),
718 country_calling_code_to_region_map.end());
719 // Sort all the pairs in ascending order according to country calling code.
720 sort(country_calling_code_to_region_code_map_->begin(),
721 country_calling_code_to_region_code_map_->end(),
725 PhoneNumberUtil::~PhoneNumberUtil() {
726 STLDeleteContainerPairSecondPointers(
727 country_calling_code_to_region_code_map_->begin(),
728 country_calling_code_to_region_code_map_->end());
731 void PhoneNumberUtil::GetSupportedRegions(set<string>* regions) const {
733 for (map<string, PhoneMetadata>::const_iterator it =
734 region_to_metadata_map_->begin(); it != region_to_metadata_map_->end();
736 regions->insert(it->first);
740 // Public wrapper function to get a PhoneNumberUtil instance with the default
743 PhoneNumberUtil* PhoneNumberUtil::GetInstance() {
744 return Singleton<PhoneNumberUtil>::GetInstance();
747 const string& PhoneNumberUtil::GetExtnPatternsForMatching() const {
748 return reg_exps_->extn_patterns_for_matching_;
751 bool PhoneNumberUtil::StartsWithPlusCharsPattern(const string& number)
753 const scoped_ptr<RegExpInput> number_string_piece(
754 reg_exps_->regexp_factory_->CreateInput(number));
755 return reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get());
758 bool PhoneNumberUtil::ContainsOnlyValidDigits(const string& s) const {
759 return reg_exps_->digits_pattern_->FullMatch(s);
762 void PhoneNumberUtil::TrimUnwantedEndChars(string* number) const {
764 UnicodeText number_as_unicode;
765 number_as_unicode.PointToUTF8(number->data(), number->size());
766 char current_char[5];
768 UnicodeText::const_reverse_iterator reverse_it(number_as_unicode.end());
769 for (; reverse_it.base() != number_as_unicode.begin(); ++reverse_it) {
770 len = reverse_it.get_utf8(current_char);
771 current_char[len] = '\0';
772 if (!reg_exps_->unwanted_end_char_pattern_->FullMatch(current_char)) {
777 number->assign(UnicodeText::UTF8Substring(number_as_unicode.begin(),
781 bool PhoneNumberUtil::IsFormatEligibleForAsYouTypeFormatter(
782 const string& format) const {
783 // A pattern that is used to determine if a numberFormat under
784 // availableFormats is eligible to be used by the AYTF. It is eligible when
785 // the format element under numberFormat contains groups of the dollar sign
786 // followed by a single digit, separated by valid phone number punctuation.
787 // This prevents invalid punctuation (such as the star sign in Israeli star
788 // numbers) getting into the output of the AYTF.
789 const RegExp& eligible_format_pattern = reg_exps_->regexp_cache_->GetRegExp(
790 StrCat("[", kValidPunctuation, "]*", "(\\$\\d", "[",
791 kValidPunctuation, "]*)+"));
792 return eligible_format_pattern.FullMatch(format);
795 bool PhoneNumberUtil::FormattingRuleHasFirstGroupOnly(
796 const string& national_prefix_formatting_rule) const {
797 // A pattern that is used to determine if the national prefix formatting rule
798 // has the first group only, i.e., does not start with the national prefix.
799 // Note that the pattern explicitly allows for unbalanced parentheses.
800 const RegExp& first_group_only_prefix_pattern =
801 reg_exps_->regexp_cache_->GetRegExp("\\(?\\$1\\)?");
802 return first_group_only_prefix_pattern.FullMatch(
803 national_prefix_formatting_rule);
806 void PhoneNumberUtil::GetNddPrefixForRegion(const string& region_code,
807 bool strip_non_digits,
808 string* national_prefix) const {
809 DCHECK(national_prefix);
810 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
812 LOG(WARNING) << "Invalid or unknown region code (" << region_code
816 national_prefix->assign(metadata->national_prefix());
817 if (strip_non_digits) {
818 // Note: if any other non-numeric symbols are ever used in national
819 // prefixes, these would have to be removed here as well.
820 strrmm(national_prefix, "~");
824 bool PhoneNumberUtil::IsValidRegionCode(const string& region_code) const {
825 return (region_to_metadata_map_->find(region_code) !=
826 region_to_metadata_map_->end());
829 bool PhoneNumberUtil::HasValidCountryCallingCode(
830 int country_calling_code) const {
831 // Create an IntRegionsPair with the country_code passed in, and use it to
832 // locate the pair with the same country_code in the sorted vector.
833 IntRegionsPair target_pair;
834 target_pair.first = country_calling_code;
835 return (binary_search(country_calling_code_to_region_code_map_->begin(),
836 country_calling_code_to_region_code_map_->end(),
837 target_pair, OrderByFirst()));
840 // Returns a pointer to the phone metadata for the appropriate region or NULL
841 // if the region code is invalid or unknown.
842 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegion(
843 const string& region_code) const {
844 map<string, PhoneMetadata>::const_iterator it =
845 region_to_metadata_map_->find(region_code);
846 if (it != region_to_metadata_map_->end()) {
852 const PhoneMetadata* PhoneNumberUtil::GetMetadataForNonGeographicalRegion(
853 int country_calling_code) const {
854 map<int, PhoneMetadata>::const_iterator it =
855 country_code_to_non_geographical_metadata_map_->find(
856 country_calling_code);
857 if (it != country_code_to_non_geographical_metadata_map_->end()) {
863 void PhoneNumberUtil::Format(const PhoneNumber& number,
864 PhoneNumberFormat number_format,
865 string* formatted_number) const {
866 DCHECK(formatted_number);
867 if (number.national_number() == 0) {
868 const string& raw_input = number.raw_input();
869 if (!raw_input.empty()) {
870 // Unparseable numbers that kept their raw input just use that.
871 // This is the only case where a number can be formatted as E164 without a
872 // leading '+' symbol (but the original number wasn't parseable anyway).
873 // TODO: Consider removing the 'if' above so that unparseable
874 // strings without raw input format to the empty string instead of "+00".
875 formatted_number->assign(raw_input);
879 int country_calling_code = number.country_code();
880 string national_significant_number;
881 GetNationalSignificantNumber(number, &national_significant_number);
882 if (number_format == E164) {
883 // Early exit for E164 case (even if the country calling code is invalid)
884 // since no formatting of the national number needs to be applied.
885 // Extensions are not formatted.
886 formatted_number->assign(national_significant_number);
887 PrefixNumberWithCountryCallingCode(country_calling_code, E164,
891 if (!HasValidCountryCallingCode(country_calling_code)) {
892 formatted_number->assign(national_significant_number);
895 // Note here that all NANPA formatting rules are contained by US, so we use
896 // that to format NANPA numbers. The same applies to Russian Fed regions -
897 // rules are contained by Russia. French Indian Ocean country rules are
898 // contained by Réunion.
900 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
901 // Metadata cannot be NULL because the country calling code is valid (which
902 // means that the region code cannot be ZZ and must be one of our supported
904 const PhoneMetadata* metadata =
905 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
906 FormatNsn(national_significant_number, *metadata, number_format,
908 MaybeAppendFormattedExtension(number, *metadata, number_format,
910 PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
914 void PhoneNumberUtil::FormatByPattern(
915 const PhoneNumber& number,
916 PhoneNumberFormat number_format,
917 const RepeatedPtrField<NumberFormat>& user_defined_formats,
918 string* formatted_number) const {
919 DCHECK(formatted_number);
920 int country_calling_code = number.country_code();
921 // Note GetRegionCodeForCountryCode() is used because formatting information
922 // for regions which share a country calling code is contained by only one
923 // region for performance reasons. For example, for NANPA regions it will be
924 // contained in the metadata for US.
925 string national_significant_number;
926 GetNationalSignificantNumber(number, &national_significant_number);
927 if (!HasValidCountryCallingCode(country_calling_code)) {
928 formatted_number->assign(national_significant_number);
932 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
933 // Metadata cannot be NULL because the country calling code is valid.
934 const PhoneMetadata* metadata =
935 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
936 const NumberFormat* formatting_pattern =
937 ChooseFormattingPatternForNumber(user_defined_formats,
938 national_significant_number);
939 if (!formatting_pattern) {
940 // If no pattern above is matched, we format the number as a whole.
941 formatted_number->assign(national_significant_number);
943 NumberFormat num_format_copy;
944 // Before we do a replacement of the national prefix pattern $NP with the
945 // national prefix, we need to copy the rule so that subsequent replacements
946 // for different numbers have the appropriate national prefix.
947 num_format_copy.MergeFrom(*formatting_pattern);
948 string national_prefix_formatting_rule(
949 formatting_pattern->national_prefix_formatting_rule());
950 if (!national_prefix_formatting_rule.empty()) {
951 const string& national_prefix = metadata->national_prefix();
952 if (!national_prefix.empty()) {
953 // Replace $NP with national prefix and $FG with the first group ($1).
954 GlobalReplaceSubstring("$NP", national_prefix,
955 &national_prefix_formatting_rule);
956 GlobalReplaceSubstring("$FG", "$1",
957 &national_prefix_formatting_rule);
958 num_format_copy.set_national_prefix_formatting_rule(
959 national_prefix_formatting_rule);
961 // We don't want to have a rule for how to format the national prefix if
963 num_format_copy.clear_national_prefix_formatting_rule();
966 FormatNsnUsingPattern(national_significant_number, num_format_copy,
967 number_format, formatted_number);
969 MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
970 PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
974 void PhoneNumberUtil::FormatNationalNumberWithCarrierCode(
975 const PhoneNumber& number,
976 const string& carrier_code,
977 string* formatted_number) const {
978 int country_calling_code = number.country_code();
979 string national_significant_number;
980 GetNationalSignificantNumber(number, &national_significant_number);
981 if (!HasValidCountryCallingCode(country_calling_code)) {
982 formatted_number->assign(national_significant_number);
986 // Note GetRegionCodeForCountryCode() is used because formatting information
987 // for regions which share a country calling code is contained by only one
988 // region for performance reasons. For example, for NANPA regions it will be
989 // contained in the metadata for US.
991 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
992 // Metadata cannot be NULL because the country calling code is valid.
993 const PhoneMetadata* metadata =
994 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
995 FormatNsnWithCarrier(national_significant_number, *metadata, NATIONAL,
996 carrier_code, formatted_number);
997 MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
998 PrefixNumberWithCountryCallingCode(country_calling_code, NATIONAL,
1002 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegionOrCallingCode(
1003 int country_calling_code, const string& region_code) const {
1004 return kRegionCodeForNonGeoEntity == region_code
1005 ? GetMetadataForNonGeographicalRegion(country_calling_code)
1006 : GetMetadataForRegion(region_code);
1009 void PhoneNumberUtil::FormatNationalNumberWithPreferredCarrierCode(
1010 const PhoneNumber& number,
1011 const string& fallback_carrier_code,
1012 string* formatted_number) const {
1013 FormatNationalNumberWithCarrierCode(
1015 number.has_preferred_domestic_carrier_code()
1016 ? number.preferred_domestic_carrier_code()
1017 : fallback_carrier_code,
1021 void PhoneNumberUtil::FormatNumberForMobileDialing(
1022 const PhoneNumber& number,
1023 const string& calling_from,
1024 bool with_formatting,
1025 string* formatted_number) const {
1026 int country_calling_code = number.country_code();
1027 if (!HasValidCountryCallingCode(country_calling_code)) {
1028 formatted_number->assign(number.has_raw_input() ? number.raw_input() : "");
1032 formatted_number->assign("");
1033 // Clear the extension, as that part cannot normally be dialed together with
1035 PhoneNumber number_no_extension(number);
1036 number_no_extension.clear_extension();
1038 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
1039 if (calling_from == region_code) {
1040 PhoneNumberType number_type = GetNumberType(number_no_extension);
1041 bool is_fixed_line_or_mobile =
1042 (number_type == FIXED_LINE) || (number_type == MOBILE) ||
1043 (number_type == FIXED_LINE_OR_MOBILE);
1044 // Carrier codes may be needed in some countries. We handle this here.
1045 if ((region_code == "CO") && (number_type == FIXED_LINE)) {
1046 FormatNationalNumberWithCarrierCode(
1047 number_no_extension, kColombiaMobileToFixedLinePrefix,
1049 } else if ((region_code == "BR") && (is_fixed_line_or_mobile)) {
1050 if (number_no_extension.has_preferred_domestic_carrier_code()) {
1051 FormatNationalNumberWithPreferredCarrierCode(number_no_extension, "",
1054 // Brazilian fixed line and mobile numbers need to be dialed with a
1055 // carrier code when called within Brazil. Without that, most of the
1056 // carriers won't connect the call. Because of that, we return an empty
1058 formatted_number->assign("");
1060 } else if (region_code == "HU") {
1061 // The national format for HU numbers doesn't contain the national prefix,
1062 // because that is how numbers are normally written down. However, the
1063 // national prefix is obligatory when dialing from a mobile phone. As a
1064 // result, we add it back here.
1065 Format(number_no_extension, NATIONAL, formatted_number);
1066 string hu_national_prefix;
1067 GetNddPrefixForRegion(region_code, true /* strip non-digits */,
1068 &hu_national_prefix);
1069 formatted_number->assign(
1070 StrCat(hu_national_prefix, " ", *formatted_number));
1072 // For NANPA countries, non-geographical countries, Mexican and Chilean
1073 // fixed line and mobile numbers, we output international format for
1074 // numbers that can be dialed internationally as that always works.
1075 if ((country_calling_code == kNanpaCountryCode ||
1076 region_code == kRegionCodeForNonGeoEntity ||
1077 // MX fixed line and mobile numbers should always be formatted in
1078 // international format, even when dialed within MX. For national
1079 // format to work, a carrier code needs to be used, and the correct
1080 // carrier code depends on if the caller and callee are from the same
1081 // local area. It is trickier to get that to work correctly than
1082 // using international format, which is tested to work fine on all
1084 // CL fixed line numbers need the national prefix when dialing in the
1085 // national format, but don't have it when used for display. The
1086 // reverse is true for mobile numbers. As a result, we output them in
1087 // the international format to make it work.
1088 ((region_code == "MX" || region_code == "CL") &&
1089 is_fixed_line_or_mobile)) &&
1090 CanBeInternationallyDialled(number_no_extension)) {
1091 Format(number_no_extension, INTERNATIONAL, formatted_number);
1093 Format(number_no_extension, NATIONAL, formatted_number);
1097 } else if (CanBeInternationallyDialled(number_no_extension)) {
1099 ? Format(number_no_extension, INTERNATIONAL, formatted_number)
1100 : Format(number_no_extension, E164, formatted_number);
1103 if (!with_formatting) {
1104 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1105 true /* remove non matches */, formatted_number);
1109 void PhoneNumberUtil::FormatOutOfCountryCallingNumber(
1110 const PhoneNumber& number,
1111 const string& calling_from,
1112 string* formatted_number) const {
1113 DCHECK(formatted_number);
1114 if (!IsValidRegionCode(calling_from)) {
1115 LOG(WARNING) << "Trying to format number from invalid region "
1117 << ". International formatting applied.";
1118 Format(number, INTERNATIONAL, formatted_number);
1121 int country_code = number.country_code();
1122 string national_significant_number;
1123 GetNationalSignificantNumber(number, &national_significant_number);
1124 if (!HasValidCountryCallingCode(country_code)) {
1125 formatted_number->assign(national_significant_number);
1128 if (country_code == kNanpaCountryCode) {
1129 if (IsNANPACountry(calling_from)) {
1130 // For NANPA regions, return the national format for these regions but
1131 // prefix it with the country calling code.
1132 Format(number, NATIONAL, formatted_number);
1133 formatted_number->insert(0, StrCat(country_code, " "));
1136 } else if (country_code == GetCountryCodeForValidRegion(calling_from)) {
1137 // If neither region is a NANPA region, then we check to see if the
1138 // country calling code of the number and the country calling code of the
1139 // region we are calling from are the same.
1140 // For regions that share a country calling code, the country calling code
1141 // need not be dialled. This also applies when dialling within a region, so
1142 // this if clause covers both these cases.
1143 // Technically this is the case for dialling from la Réunion to other
1144 // overseas departments of France (French Guiana, Martinique, Guadeloupe),
1145 // but not vice versa - so we don't cover this edge case for now and for
1146 // those cases return the version including country calling code.
1148 // http://www.petitfute.com/voyage/225-info-pratiques-reunion
1149 Format(number, NATIONAL, formatted_number);
1152 // Metadata cannot be NULL because we checked 'IsValidRegionCode()' above.
1153 const PhoneMetadata* metadata_calling_from =
1154 GetMetadataForRegion(calling_from);
1155 const string& international_prefix =
1156 metadata_calling_from->international_prefix();
1158 // For regions that have multiple international prefixes, the international
1159 // format of the number is returned, unless there is a preferred international
1161 const string international_prefix_for_formatting(
1162 reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1163 ? international_prefix
1164 : metadata_calling_from->preferred_international_prefix());
1167 GetRegionCodeForCountryCode(country_code, ®ion_code);
1168 // Metadata cannot be NULL because the country_code is valid.
1169 const PhoneMetadata* metadata_for_region =
1170 GetMetadataForRegionOrCallingCode(country_code, region_code);
1171 FormatNsn(national_significant_number, *metadata_for_region, INTERNATIONAL,
1173 MaybeAppendFormattedExtension(number, *metadata_for_region, INTERNATIONAL,
1175 if (!international_prefix_for_formatting.empty()) {
1176 formatted_number->insert(
1177 0, StrCat(international_prefix_for_formatting, " ", country_code, " "));
1179 PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1184 void PhoneNumberUtil::FormatInOriginalFormat(const PhoneNumber& number,
1185 const string& region_calling_from,
1186 string* formatted_number) const {
1187 DCHECK(formatted_number);
1189 if (number.has_raw_input() &&
1190 (HasUnexpectedItalianLeadingZero(number) ||
1191 !HasFormattingPatternForNumber(number))) {
1192 // We check if we have the formatting pattern because without that, we might
1193 // format the number as a group without national prefix.
1194 formatted_number->assign(number.raw_input());
1197 if (!number.has_country_code_source()) {
1198 Format(number, NATIONAL, formatted_number);
1201 switch (number.country_code_source()) {
1202 case PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN:
1203 Format(number, INTERNATIONAL, formatted_number);
1205 case PhoneNumber::FROM_NUMBER_WITH_IDD:
1206 FormatOutOfCountryCallingNumber(number, region_calling_from,
1209 case PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN:
1210 Format(number, INTERNATIONAL, formatted_number);
1211 formatted_number->erase(formatted_number->begin());
1213 case PhoneNumber::FROM_DEFAULT_COUNTRY:
1214 // Fall-through to default case.
1217 GetRegionCodeForCountryCode(number.country_code(), ®ion_code);
1218 // We strip non-digits from the NDD here, and from the raw input later, so
1219 // that we can compare them easily.
1220 string national_prefix;
1221 GetNddPrefixForRegion(region_code, true /* strip non-digits */,
1223 if (national_prefix.empty()) {
1224 // If the region doesn't have a national prefix at all, we can safely
1225 // return the national format without worrying about a national prefix
1227 Format(number, NATIONAL, formatted_number);
1230 // Otherwise, we check if the original number was entered with a national
1232 if (RawInputContainsNationalPrefix(number.raw_input(), national_prefix,
1234 // If so, we can safely return the national format.
1235 Format(number, NATIONAL, formatted_number);
1238 // Metadata cannot be NULL here because GetNddPrefixForRegion() (above)
1239 // leaves the prefix empty if there is no metadata for the region.
1240 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1241 string national_number;
1242 GetNationalSignificantNumber(number, &national_number);
1243 // This shouldn't be NULL, because we have checked that above with
1244 // HasFormattingPatternForNumber.
1245 const NumberFormat* format_rule =
1246 ChooseFormattingPatternForNumber(metadata->number_format(),
1248 // The format rule could still be NULL here if the national number was 0
1249 // and there was no raw input (this should not be possible for numbers
1250 // generated by the phonenumber library as they would also not have a
1251 // country calling code and we would have exited earlier).
1253 Format(number, NATIONAL, formatted_number);
1256 // When the format we apply to this number doesn't contain national
1257 // prefix, we can just return the national format.
1258 // TODO: Refactor the code below with the code in
1259 // IsNationalPrefixPresentIfRequired.
1260 string candidate_national_prefix_rule(
1261 format_rule->national_prefix_formatting_rule());
1262 // We assume that the first-group symbol will never be _before_ the
1264 if (!candidate_national_prefix_rule.empty()) {
1265 candidate_national_prefix_rule.erase(
1266 candidate_national_prefix_rule.find("$1"));
1267 NormalizeDigitsOnly(&candidate_national_prefix_rule);
1269 if (candidate_national_prefix_rule.empty()) {
1270 // National prefix not used when formatting this number.
1271 Format(number, NATIONAL, formatted_number);
1274 // Otherwise, we need to remove the national prefix from our output.
1275 RepeatedPtrField<NumberFormat> number_formats;
1276 NumberFormat* number_format = number_formats.Add();
1277 number_format->MergeFrom(*format_rule);
1278 number_format->clear_national_prefix_formatting_rule();
1279 FormatByPattern(number, NATIONAL, number_formats, formatted_number);
1282 // If no digit is inserted/removed/modified as a result of our formatting, we
1283 // return the formatted phone number; otherwise we return the raw input the
1285 if (!formatted_number->empty() && !number.raw_input().empty()) {
1286 string normalized_formatted_number(*formatted_number);
1287 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1288 true /* remove non matches */,
1289 &normalized_formatted_number);
1290 string normalized_raw_input(number.raw_input());
1291 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1292 true /* remove non matches */, &normalized_raw_input);
1293 if (normalized_formatted_number != normalized_raw_input) {
1294 formatted_number->assign(number.raw_input());
1299 // Check if raw_input, which is assumed to be in the national format, has a
1300 // national prefix. The national prefix is assumed to be in digits-only form.
1301 bool PhoneNumberUtil::RawInputContainsNationalPrefix(
1302 const string& raw_input,
1303 const string& national_prefix,
1304 const string& region_code) const {
1305 string normalized_national_number(raw_input);
1306 NormalizeDigitsOnly(&normalized_national_number);
1307 if (HasPrefixString(normalized_national_number, national_prefix)) {
1308 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain
1309 // the national prefix when written without it (e.g. 0777123) if we just
1310 // do prefix matching. To tackle that, we check the validity of the
1311 // number if the assumed national prefix is removed (777123 won't be
1313 PhoneNumber number_without_national_prefix;
1314 if (Parse(normalized_national_number.substr(national_prefix.length()),
1315 region_code, &number_without_national_prefix)
1316 == NO_PARSING_ERROR) {
1317 return IsValidNumber(number_without_national_prefix);
1323 bool PhoneNumberUtil::HasUnexpectedItalianLeadingZero(
1324 const PhoneNumber& number) const {
1325 return number.has_italian_leading_zero() &&
1326 !IsLeadingZeroPossible(number.country_code());
1329 bool PhoneNumberUtil::HasFormattingPatternForNumber(
1330 const PhoneNumber& number) const {
1331 int country_calling_code = number.country_code();
1333 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
1334 const PhoneMetadata* metadata =
1335 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
1339 string national_number;
1340 GetNationalSignificantNumber(number, &national_number);
1341 const NumberFormat* format_rule =
1342 ChooseFormattingPatternForNumber(metadata->number_format(),
1347 void PhoneNumberUtil::FormatOutOfCountryKeepingAlphaChars(
1348 const PhoneNumber& number,
1349 const string& calling_from,
1350 string* formatted_number) const {
1351 // If there is no raw input, then we can't keep alpha characters because there
1352 // aren't any. In this case, we return FormatOutOfCountryCallingNumber.
1353 if (number.raw_input().empty()) {
1354 FormatOutOfCountryCallingNumber(number, calling_from, formatted_number);
1357 int country_code = number.country_code();
1358 if (!HasValidCountryCallingCode(country_code)) {
1359 formatted_number->assign(number.raw_input());
1362 // Strip any prefix such as country calling code, IDD, that was present. We do
1363 // this by comparing the number in raw_input with the parsed number.
1364 string raw_input_copy(number.raw_input());
1365 // Normalize punctuation. We retain number grouping symbols such as " " only.
1366 NormalizeHelper(reg_exps_->all_plus_number_grouping_symbols_, true,
1368 // Now we trim everything before the first three digits in the parsed number.
1369 // We choose three because all valid alpha numbers have 3 digits at the start
1370 // - if it does not, then we don't trim anything at all. Similarly, if the
1371 // national number was less than three digits, we don't trim anything at all.
1372 string national_number;
1373 GetNationalSignificantNumber(number, &national_number);
1374 if (national_number.length() > 3) {
1375 size_t first_national_number_digit =
1376 raw_input_copy.find(national_number.substr(0, 3));
1377 if (first_national_number_digit != string::npos) {
1378 raw_input_copy = raw_input_copy.substr(first_national_number_digit);
1381 const PhoneMetadata* metadata = GetMetadataForRegion(calling_from);
1382 if (country_code == kNanpaCountryCode) {
1383 if (IsNANPACountry(calling_from)) {
1384 StrAppend(formatted_number, country_code, " ", raw_input_copy);
1387 } else if (metadata &&
1388 country_code == GetCountryCodeForValidRegion(calling_from)) {
1389 const NumberFormat* formatting_pattern =
1390 ChooseFormattingPatternForNumber(metadata->number_format(),
1392 if (!formatting_pattern) {
1393 // If no pattern above is matched, we format the original input.
1394 formatted_number->assign(raw_input_copy);
1397 NumberFormat new_format;
1398 new_format.MergeFrom(*formatting_pattern);
1399 // The first group is the first group of digits that the user wrote
1401 new_format.set_pattern("(\\d+)(.*)");
1402 // Here we just concatenate them back together after the national prefix
1404 new_format.set_format("$1$2");
1405 // Now we format using this pattern instead of the default pattern, but
1406 // with the national prefix prefixed if necessary.
1407 // This will not work in the cases where the pattern (and not the
1408 // leading digits) decide whether a national prefix needs to be used, since
1409 // we have overridden the pattern to match anything, but that is not the
1410 // case in the metadata to date.
1411 FormatNsnUsingPattern(raw_input_copy, new_format, NATIONAL,
1416 string international_prefix_for_formatting;
1417 // If an unsupported region-calling-from is entered, or a country with
1418 // multiple international prefixes, the international format of the number is
1419 // returned, unless there is a preferred international prefix.
1421 const string& international_prefix = metadata->international_prefix();
1422 international_prefix_for_formatting =
1423 reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1424 ? international_prefix
1425 : metadata->preferred_international_prefix();
1427 if (!international_prefix_for_formatting.empty()) {
1428 StrAppend(formatted_number, international_prefix_for_formatting, " ",
1429 country_code, " ", raw_input_copy);
1431 // Invalid region entered as country-calling-from (so no metadata was found
1432 // for it) or the region chosen has multiple international dialling
1434 LOG(WARNING) << "Trying to format number from invalid region "
1436 << ". International formatting applied.";
1437 formatted_number->assign(raw_input_copy);
1438 PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1443 const NumberFormat* PhoneNumberUtil::ChooseFormattingPatternForNumber(
1444 const RepeatedPtrField<NumberFormat>& available_formats,
1445 const string& national_number) const {
1446 for (RepeatedPtrField<NumberFormat>::const_iterator
1447 it = available_formats.begin(); it != available_formats.end(); ++it) {
1448 int size = it->leading_digits_pattern_size();
1450 const scoped_ptr<RegExpInput> number_copy(
1451 reg_exps_->regexp_factory_->CreateInput(national_number));
1452 // We always use the last leading_digits_pattern, as it is the most
1454 if (!reg_exps_->regexp_cache_->GetRegExp(
1455 it->leading_digits_pattern(size - 1)).Consume(
1456 number_copy.get())) {
1460 const RegExp& pattern_to_match(
1461 reg_exps_->regexp_cache_->GetRegExp(it->pattern()));
1462 if (pattern_to_match.FullMatch(national_number)) {
1469 // Note that carrier_code is optional - if an empty string, no carrier code
1470 // replacement will take place.
1471 void PhoneNumberUtil::FormatNsnUsingPatternWithCarrier(
1472 const string& national_number,
1473 const NumberFormat& formatting_pattern,
1474 PhoneNumberUtil::PhoneNumberFormat number_format,
1475 const string& carrier_code,
1476 string* formatted_number) const {
1477 DCHECK(formatted_number);
1478 string number_format_rule(formatting_pattern.format());
1479 if (number_format == PhoneNumberUtil::NATIONAL &&
1480 carrier_code.length() > 0 &&
1481 formatting_pattern.domestic_carrier_code_formatting_rule().length() > 0) {
1482 // Replace the $CC in the formatting rule with the desired carrier code.
1483 string carrier_code_formatting_rule =
1484 formatting_pattern.domestic_carrier_code_formatting_rule();
1485 reg_exps_->carrier_code_pattern_->Replace(&carrier_code_formatting_rule,
1487 reg_exps_->first_group_capturing_pattern_->
1488 Replace(&number_format_rule, carrier_code_formatting_rule);
1490 // Use the national prefix formatting rule instead.
1491 string national_prefix_formatting_rule =
1492 formatting_pattern.national_prefix_formatting_rule();
1493 if (number_format == PhoneNumberUtil::NATIONAL &&
1494 national_prefix_formatting_rule.length() > 0) {
1495 // Apply the national_prefix_formatting_rule as the formatting_pattern
1496 // contains only information on how the national significant number
1497 // should be formatted at this point.
1498 reg_exps_->first_group_capturing_pattern_->Replace(
1499 &number_format_rule, national_prefix_formatting_rule);
1502 formatted_number->assign(national_number);
1504 const RegExp& pattern_to_match(
1505 reg_exps_->regexp_cache_->GetRegExp(formatting_pattern.pattern()));
1506 pattern_to_match.GlobalReplace(formatted_number, number_format_rule);
1508 if (number_format == RFC3966) {
1509 // First consume any leading punctuation, if any was present.
1510 const scoped_ptr<RegExpInput> number(
1511 reg_exps_->regexp_factory_->CreateInput(*formatted_number));
1512 if (reg_exps_->separator_pattern_->Consume(number.get())) {
1513 formatted_number->assign(number->ToString());
1515 // Then replace all separators with a "-".
1516 reg_exps_->separator_pattern_->GlobalReplace(formatted_number, "-");
1520 // Simple wrapper of FormatNsnUsingPatternWithCarrier for the common case of
1522 void PhoneNumberUtil::FormatNsnUsingPattern(
1523 const string& national_number,
1524 const NumberFormat& formatting_pattern,
1525 PhoneNumberUtil::PhoneNumberFormat number_format,
1526 string* formatted_number) const {
1527 DCHECK(formatted_number);
1528 FormatNsnUsingPatternWithCarrier(national_number, formatting_pattern,
1529 number_format, "", formatted_number);
1532 void PhoneNumberUtil::FormatNsn(const string& number,
1533 const PhoneMetadata& metadata,
1534 PhoneNumberFormat number_format,
1535 string* formatted_number) const {
1536 DCHECK(formatted_number);
1537 FormatNsnWithCarrier(number, metadata, number_format, "", formatted_number);
1540 // Note in some regions, the national number can be written in two completely
1541 // different ways depending on whether it forms part of the NATIONAL format or
1542 // INTERNATIONAL format. The number_format parameter here is used to specify
1543 // which format to use for those cases. If a carrier_code is specified, this
1544 // will be inserted into the formatted string to replace $CC.
1545 void PhoneNumberUtil::FormatNsnWithCarrier(const string& number,
1546 const PhoneMetadata& metadata,
1547 PhoneNumberFormat number_format,
1548 const string& carrier_code,
1549 string* formatted_number) const {
1550 DCHECK(formatted_number);
1551 // When the intl_number_formats exists, we use that to format national number
1552 // for the INTERNATIONAL format instead of using the number_formats.
1553 const RepeatedPtrField<NumberFormat> available_formats =
1554 (metadata.intl_number_format_size() == 0 || number_format == NATIONAL)
1555 ? metadata.number_format()
1556 : metadata.intl_number_format();
1557 const NumberFormat* formatting_pattern =
1558 ChooseFormattingPatternForNumber(available_formats, number);
1559 if (!formatting_pattern) {
1560 formatted_number->assign(number);
1562 FormatNsnUsingPatternWithCarrier(number, *formatting_pattern, number_format,
1563 carrier_code, formatted_number);
1567 // Appends the formatted extension of a phone number, if the phone number had an
1568 // extension specified.
1569 void PhoneNumberUtil::MaybeAppendFormattedExtension(
1570 const PhoneNumber& number,
1571 const PhoneMetadata& metadata,
1572 PhoneNumberFormat number_format,
1573 string* formatted_number) const {
1574 DCHECK(formatted_number);
1575 if (number.has_extension() && number.extension().length() > 0) {
1576 if (number_format == RFC3966) {
1577 StrAppend(formatted_number, kRfc3966ExtnPrefix, number.extension());
1579 if (metadata.has_preferred_extn_prefix()) {
1580 StrAppend(formatted_number, metadata.preferred_extn_prefix(),
1581 number.extension());
1583 StrAppend(formatted_number, kDefaultExtnPrefix, number.extension());
1589 bool PhoneNumberUtil::IsNANPACountry(const string& region_code) const {
1590 return nanpa_regions_->find(region_code) != nanpa_regions_->end();
1593 // Returns the region codes that matches the specific country calling code. In
1594 // the case of no region code being found, region_codes will be left empty.
1595 void PhoneNumberUtil::GetRegionCodesForCountryCallingCode(
1596 int country_calling_code,
1597 list<string>* region_codes) const {
1598 DCHECK(region_codes);
1599 // Create a IntRegionsPair with the country_code passed in, and use it to
1600 // locate the pair with the same country_code in the sorted vector.
1601 IntRegionsPair target_pair;
1602 target_pair.first = country_calling_code;
1603 typedef vector<IntRegionsPair>::const_iterator ConstIterator;
1604 pair<ConstIterator, ConstIterator> range = equal_range(
1605 country_calling_code_to_region_code_map_->begin(),
1606 country_calling_code_to_region_code_map_->end(),
1607 target_pair, OrderByFirst());
1608 if (range.first != range.second) {
1609 region_codes->insert(region_codes->begin(),
1610 range.first->second->begin(),
1611 range.first->second->end());
1615 // Returns the region code that matches the specific country calling code. In
1616 // the case of no region code being found, the unknown region code will be
1618 void PhoneNumberUtil::GetRegionCodeForCountryCode(
1619 int country_calling_code,
1620 string* region_code) const {
1621 DCHECK(region_code);
1622 list<string> region_codes;
1624 GetRegionCodesForCountryCallingCode(country_calling_code, ®ion_codes);
1625 *region_code = (region_codes.size() > 0) ?
1626 region_codes.front() : RegionCode::GetUnknown();
1629 void PhoneNumberUtil::GetRegionCodeForNumber(const PhoneNumber& number,
1630 string* region_code) const {
1631 DCHECK(region_code);
1632 int country_calling_code = number.country_code();
1633 list<string> region_codes;
1634 GetRegionCodesForCountryCallingCode(country_calling_code, ®ion_codes);
1635 if (region_codes.size() == 0) {
1636 string number_string;
1637 GetNationalSignificantNumber(number, &number_string);
1638 LOG(WARNING) << "Missing/invalid country calling code ("
1639 << country_calling_code
1640 << ") for number " << number_string;
1641 *region_code = RegionCode::GetUnknown();
1644 if (region_codes.size() == 1) {
1645 *region_code = region_codes.front();
1647 GetRegionCodeForNumberFromRegionList(number, region_codes, region_code);
1651 void PhoneNumberUtil::GetRegionCodeForNumberFromRegionList(
1652 const PhoneNumber& number, const list<string>& region_codes,
1653 string* region_code) const {
1654 DCHECK(region_code);
1655 string national_number;
1656 GetNationalSignificantNumber(number, &national_number);
1657 for (list<string>::const_iterator it = region_codes.begin();
1658 it != region_codes.end(); ++it) {
1659 // Metadata cannot be NULL because the region codes come from the country
1660 // calling code map.
1661 const PhoneMetadata* metadata = GetMetadataForRegion(*it);
1662 if (metadata->has_leading_digits()) {
1663 const scoped_ptr<RegExpInput> number(
1664 reg_exps_->regexp_factory_->CreateInput(national_number));
1665 if (reg_exps_->regexp_cache_->
1666 GetRegExp(metadata->leading_digits()).Consume(number.get())) {
1670 } else if (GetNumberTypeHelper(national_number, *metadata,
1671 reg_exps_->regexp_cache_.get()) != UNKNOWN) {
1676 *region_code = RegionCode::GetUnknown();
1679 int PhoneNumberUtil::GetCountryCodeForRegion(const string& region_code) const {
1680 if (!IsValidRegionCode(region_code)) {
1681 LOG(WARNING) << "Invalid or unknown region code (" << region_code
1685 return GetCountryCodeForValidRegion(region_code);
1688 int PhoneNumberUtil::GetCountryCodeForValidRegion(
1689 const string& region_code) const {
1690 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1691 return metadata->country_code();
1694 // Gets a valid fixed-line number for the specified region_code. Returns false
1695 // if the region was unknown or 001 (representing non-geographical regions), or
1696 // if no number exists.
1697 bool PhoneNumberUtil::GetExampleNumber(const string& region_code,
1698 PhoneNumber* number) const {
1700 return GetExampleNumberForType(region_code, FIXED_LINE, number);
1703 // Gets a valid number for the specified region_code and type. Returns false if
1704 // the country was unknown or 001 (representing non-geographical regions), or if
1705 // no number exists.
1706 bool PhoneNumberUtil::GetExampleNumberForType(
1707 const string& region_code,
1708 PhoneNumberUtil::PhoneNumberType type,
1709 PhoneNumber* number) const {
1711 if (!IsValidRegionCode(region_code)) {
1712 LOG(WARNING) << "Invalid or unknown region code (" << region_code
1716 const PhoneMetadata* region_metadata = GetMetadataForRegion(region_code);
1717 const PhoneNumberDesc* desc = GetNumberDescByType(*region_metadata, type);
1718 if (desc && desc->has_example_number()) {
1719 ErrorType success = Parse(desc->example_number(), region_code, number);
1720 if (success == NO_PARSING_ERROR) {
1723 LOG(ERROR) << "Error parsing example number ("
1724 << static_cast<int>(success) << ")";
1730 bool PhoneNumberUtil::GetExampleNumberForNonGeoEntity(
1731 int country_calling_code, PhoneNumber* number) const {
1733 const PhoneMetadata* metadata =
1734 GetMetadataForNonGeographicalRegion(country_calling_code);
1736 const PhoneNumberDesc& desc = metadata->general_desc();
1737 if (desc.has_example_number()) {
1738 ErrorType success = Parse(StrCat(kPlusSign,
1739 SimpleItoa(country_calling_code),
1740 desc.example_number()),
1741 RegionCode::ZZ(), number);
1742 if (success == NO_PARSING_ERROR) {
1745 LOG(ERROR) << "Error parsing example number ("
1746 << static_cast<int>(success) << ")";
1750 LOG(WARNING) << "Invalid or unknown country calling code provided: "
1751 << country_calling_code;
1756 PhoneNumberUtil::ErrorType PhoneNumberUtil::Parse(const string& number_to_parse,
1757 const string& default_region,
1758 PhoneNumber* number) const {
1760 return ParseHelper(number_to_parse, default_region, false, true, number);
1763 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseAndKeepRawInput(
1764 const string& number_to_parse,
1765 const string& default_region,
1766 PhoneNumber* number) const {
1768 return ParseHelper(number_to_parse, default_region, true, true, number);
1771 // Checks to see that the region code used is valid, or if it is not valid, that
1772 // the number to parse starts with a + symbol so that we can attempt to infer
1773 // the country from the number. Returns false if it cannot use the region
1774 // provided and the region cannot be inferred.
1775 bool PhoneNumberUtil::CheckRegionForParsing(
1776 const string& number_to_parse,
1777 const string& default_region) const {
1778 if (!IsValidRegionCode(default_region) && !number_to_parse.empty()) {
1779 const scoped_ptr<RegExpInput> number(
1780 reg_exps_->regexp_factory_->CreateInput(number_to_parse));
1781 if (!reg_exps_->plus_chars_pattern_->Consume(number.get())) {
1788 // Converts number_to_parse to a form that we can parse and write it to
1789 // national_number if it is written in RFC3966; otherwise extract a possible
1790 // number out of it and write to national_number.
1791 void PhoneNumberUtil::BuildNationalNumberForParsing(
1792 const string& number_to_parse, string* national_number) const {
1793 size_t index_of_phone_context = number_to_parse.find(kRfc3966PhoneContext);
1794 if (index_of_phone_context != string::npos) {
1795 int phone_context_start =
1796 index_of_phone_context + strlen(kRfc3966PhoneContext);
1797 // If the phone context contains a phone number prefix, we need to capture
1798 // it, whereas domains will be ignored.
1799 if (number_to_parse.at(phone_context_start) == kPlusSign[0]) {
1800 // Additional parameters might follow the phone context. If so, we will
1801 // remove them here because the parameters after phone context are not
1802 // important for parsing the phone number.
1803 size_t phone_context_end = number_to_parse.find(';', phone_context_start);
1804 if (phone_context_end != string::npos) {
1806 national_number, number_to_parse.substr(
1807 phone_context_start, phone_context_end - phone_context_start));
1809 StrAppend(national_number, number_to_parse.substr(phone_context_start));
1813 // Now append everything between the "tel:" prefix and the phone-context.
1814 // This should include the national number, an optional extension or
1815 // isdn-subaddress component.
1816 int end_of_rfc_prefix =
1817 number_to_parse.find(kRfc3966Prefix) + strlen(kRfc3966Prefix);
1820 number_to_parse.substr(end_of_rfc_prefix,
1821 index_of_phone_context - end_of_rfc_prefix));
1823 // Extract a possible number from the string passed in (this strips leading
1824 // characters that could not be the start of a phone number.)
1825 ExtractPossibleNumber(number_to_parse, national_number);
1828 // Delete the isdn-subaddress and everything after it if it is present. Note
1829 // extension won't appear at the same time with isdn-subaddress according to
1830 // paragraph 5.3 of the RFC3966 spec.
1831 size_t index_of_isdn = national_number->find(kRfc3966IsdnSubaddress);
1832 if (index_of_isdn != string::npos) {
1833 national_number->erase(index_of_isdn);
1835 // If both phone context and isdn-subaddress are absent but other parameters
1836 // are present, the parameters are left in nationalNumber. This is because
1837 // we are concerned about deleting content from a potential number string
1838 // when there is no strong evidence that the number is actually written in
1842 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseHelper(
1843 const string& number_to_parse,
1844 const string& default_region,
1845 bool keep_raw_input,
1847 PhoneNumber* phone_number) const {
1848 DCHECK(phone_number);
1850 string national_number;
1851 BuildNationalNumberForParsing(number_to_parse, &national_number);
1853 if (!IsViablePhoneNumber(national_number)) {
1854 VLOG(2) << "The string supplied did not seem to be a phone number.";
1855 return NOT_A_NUMBER;
1859 !CheckRegionForParsing(national_number, default_region)) {
1860 VLOG(1) << "Missing or invalid default country.";
1861 return INVALID_COUNTRY_CODE_ERROR;
1863 PhoneNumber temp_number;
1864 if (keep_raw_input) {
1865 temp_number.set_raw_input(number_to_parse);
1867 // Attempt to parse extension first, since it doesn't require country-specific
1868 // data and we want to have the non-normalised number here.
1870 MaybeStripExtension(&national_number, &extension);
1871 if (!extension.empty()) {
1872 temp_number.set_extension(extension);
1874 const PhoneMetadata* country_metadata = GetMetadataForRegion(default_region);
1875 // Check to see if the number is given in international format so we know
1876 // whether this number is from the default country or not.
1877 string normalized_national_number(national_number);
1878 ErrorType country_code_error =
1879 MaybeExtractCountryCode(country_metadata, keep_raw_input,
1880 &normalized_national_number, &temp_number);
1881 if (country_code_error != NO_PARSING_ERROR) {
1882 const scoped_ptr<RegExpInput> number_string_piece(
1883 reg_exps_->regexp_factory_->CreateInput(national_number));
1884 if ((country_code_error == INVALID_COUNTRY_CODE_ERROR) &&
1885 (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get()))) {
1886 normalized_national_number.assign(number_string_piece->ToString());
1887 // Strip the plus-char, and try again.
1888 MaybeExtractCountryCode(country_metadata,
1890 &normalized_national_number,
1892 if (temp_number.country_code() == 0) {
1893 return INVALID_COUNTRY_CODE_ERROR;
1896 return country_code_error;
1899 int country_code = temp_number.country_code();
1900 if (country_code != 0) {
1901 string phone_number_region;
1902 GetRegionCodeForCountryCode(country_code, &phone_number_region);
1903 if (phone_number_region != default_region) {
1905 GetMetadataForRegionOrCallingCode(country_code, phone_number_region);
1907 } else if (country_metadata) {
1908 // If no extracted country calling code, use the region supplied instead.
1909 // Note that the national number was already normalized by
1910 // MaybeExtractCountryCode.
1911 country_code = country_metadata->country_code();
1913 if (normalized_national_number.length() < kMinLengthForNsn) {
1914 VLOG(2) << "The string supplied is too short to be a phone number.";
1915 return TOO_SHORT_NSN;
1917 if (country_metadata) {
1918 string* carrier_code = keep_raw_input ?
1919 temp_number.mutable_preferred_domestic_carrier_code() : NULL;
1920 MaybeStripNationalPrefixAndCarrierCode(*country_metadata,
1921 &normalized_national_number,
1924 size_t normalized_national_number_length =
1925 normalized_national_number.length();
1926 if (normalized_national_number_length < kMinLengthForNsn) {
1927 VLOG(2) << "The string supplied is too short to be a phone number.";
1928 return TOO_SHORT_NSN;
1930 if (normalized_national_number_length > kMaxLengthForNsn) {
1931 VLOG(2) << "The string supplied is too long to be a phone number.";
1932 return TOO_LONG_NSN;
1934 temp_number.set_country_code(country_code);
1935 if (normalized_national_number[0] == '0') {
1936 temp_number.set_italian_leading_zero(true);
1938 uint64 number_as_int;
1939 safe_strtou64(normalized_national_number, &number_as_int);
1940 temp_number.set_national_number(number_as_int);
1941 phone_number->MergeFrom(temp_number);
1942 return NO_PARSING_ERROR;
1945 // Attempts to extract a possible number from the string passed in. This
1946 // currently strips all leading characters that could not be used to start a
1947 // phone number. Characters that can be used to start a phone number are
1948 // defined in the valid_start_char_pattern. If none of these characters are
1949 // found in the number passed in, an empty string is returned. This function
1950 // also attempts to strip off any alternative extensions or endings if two or
1951 // more are present, such as in the case of: (530) 583-6985 x302/x2303. The
1952 // second extension here makes this actually two phone numbers, (530) 583-6985
1953 // x302 and (530) 583-6985 x2303. We remove the second extension so that the
1954 // first number is parsed correctly.
1955 void PhoneNumberUtil::ExtractPossibleNumber(const string& number,
1956 string* extracted_number) const {
1957 DCHECK(extracted_number);
1959 UnicodeText number_as_unicode;
1960 number_as_unicode.PointToUTF8(number.data(), number.size());
1961 char current_char[5];
1963 UnicodeText::const_iterator it;
1964 for (it = number_as_unicode.begin(); it != number_as_unicode.end(); ++it) {
1965 len = it.get_utf8(current_char);
1966 current_char[len] = '\0';
1967 if (reg_exps_->valid_start_char_pattern_->FullMatch(current_char)) {
1972 if (it == number_as_unicode.end()) {
1973 // No valid start character was found. extracted_number should be set to
1975 extracted_number->assign("");
1979 extracted_number->assign(
1980 UnicodeText::UTF8Substring(it, number_as_unicode.end()));
1981 TrimUnwantedEndChars(extracted_number);
1982 if (extracted_number->length() == 0) {
1986 VLOG(3) << "After stripping starting and trailing characters, left with: "
1987 << *extracted_number;
1989 // Now remove any extra numbers at the end.
1990 reg_exps_->capture_up_to_second_number_start_pattern_->
1991 PartialMatch(*extracted_number, extracted_number);
1994 bool PhoneNumberUtil::IsPossibleNumber(const PhoneNumber& number) const {
1995 return IsPossibleNumberWithReason(number) == IS_POSSIBLE;
1998 bool PhoneNumberUtil::IsPossibleNumberForString(
1999 const string& number,
2000 const string& region_dialing_from) const {
2001 PhoneNumber number_proto;
2002 if (Parse(number, region_dialing_from, &number_proto) == NO_PARSING_ERROR) {
2003 return IsPossibleNumber(number_proto);
2009 PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberWithReason(
2010 const PhoneNumber& number) const {
2011 string national_number;
2012 GetNationalSignificantNumber(number, &national_number);
2013 int country_code = number.country_code();
2014 // Note: For Russian Fed and NANPA numbers, we just use the rules from the
2015 // default region (US or Russia) since the GetRegionCodeForNumber will not
2016 // work if the number is possible but not valid. This would need to be
2017 // revisited if the possible number pattern ever differed between various
2018 // regions within those plans.
2019 if (!HasValidCountryCallingCode(country_code)) {
2020 return INVALID_COUNTRY_CODE;
2023 GetRegionCodeForCountryCode(country_code, ®ion_code);
2024 // Metadata cannot be NULL because the country calling code is valid.
2025 const PhoneMetadata* metadata =
2026 GetMetadataForRegionOrCallingCode(country_code, region_code);
2027 const PhoneNumberDesc& general_num_desc = metadata->general_desc();
2028 // Handling case of numbers with no metadata.
2029 if (!general_num_desc.has_national_number_pattern()) {
2030 size_t number_length = national_number.length();
2031 if (number_length < kMinLengthForNsn) {
2033 } else if (number_length > kMaxLengthForNsn) {
2039 const RegExp& possible_number_pattern = reg_exps_->regexp_cache_->GetRegExp(
2040 StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2041 return TestNumberLengthAgainstPattern(possible_number_pattern,
2045 bool PhoneNumberUtil::TruncateTooLongNumber(PhoneNumber* number) const {
2046 if (IsValidNumber(*number)) {
2049 PhoneNumber number_copy(*number);
2050 uint64 national_number = number->national_number();
2052 national_number /= 10;
2053 number_copy.set_national_number(national_number);
2054 if (IsPossibleNumberWithReason(number_copy) == TOO_SHORT ||
2055 national_number == 0) {
2058 } while (!IsValidNumber(number_copy));
2059 number->set_national_number(national_number);
2063 PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberType(
2064 const PhoneNumber& number) const {
2066 GetRegionCodeForNumber(number, ®ion_code);
2067 const PhoneMetadata* metadata =
2068 GetMetadataForRegionOrCallingCode(number.country_code(), region_code);
2072 string national_significant_number;
2073 GetNationalSignificantNumber(number, &national_significant_number);
2074 return GetNumberTypeHelper(national_significant_number,
2076 reg_exps_->regexp_cache_.get());
2079 bool PhoneNumberUtil::IsValidNumber(const PhoneNumber& number) const {
2081 GetRegionCodeForNumber(number, ®ion_code);
2082 return IsValidNumberForRegion(number, region_code);
2085 bool PhoneNumberUtil::IsValidNumberForRegion(const PhoneNumber& number,
2086 const string& region_code) const {
2087 int country_code = number.country_code();
2088 const PhoneMetadata* metadata =
2089 GetMetadataForRegionOrCallingCode(country_code, region_code);
2091 ((kRegionCodeForNonGeoEntity != region_code) &&
2092 country_code != GetCountryCodeForValidRegion(region_code))) {
2093 // Either the region code was invalid, or the country calling code for this
2094 // number does not match that of the region code.
2097 const PhoneNumberDesc& general_desc = metadata->general_desc();
2098 string national_number;
2099 GetNationalSignificantNumber(number, &national_number);
2101 // For regions where we don't have metadata for PhoneNumberDesc, we treat
2102 // any number passed in as a valid number if its national significant number
2103 // is between the minimum and maximum lengths defined by ITU for a national
2104 // significant number.
2105 if (!general_desc.has_national_number_pattern()) {
2106 VLOG(3) << "Validating number with incomplete metadata.";
2107 size_t number_length = national_number.length();
2108 return number_length > kMinLengthForNsn &&
2109 number_length <= kMaxLengthForNsn;
2111 return GetNumberTypeHelper(national_number, *metadata,
2112 reg_exps_->regexp_cache_.get()) != UNKNOWN;
2115 bool PhoneNumberUtil::IsNumberGeographical(
2116 const PhoneNumber& phone_number) const {
2117 PhoneNumberType number_type = GetNumberType(phone_number);
2118 // TODO: Include mobile phone numbers from countries like
2119 // Indonesia, which has some mobile numbers that are geographical.
2120 return number_type == PhoneNumberUtil::FIXED_LINE ||
2121 number_type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
2124 bool PhoneNumberUtil::IsLeadingZeroPossible(int country_calling_code) const {
2126 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
2127 const PhoneMetadata* main_metadata_for_calling_code =
2128 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
2129 if (!main_metadata_for_calling_code) return false;
2130 return main_metadata_for_calling_code->leading_zero_possible();
2133 void PhoneNumberUtil::GetNationalSignificantNumber(
2134 const PhoneNumber& number,
2135 string* national_number) const {
2136 DCHECK(national_number);
2137 // If a leading zero has been set, we prefix this now. Note this is not a
2139 StrAppend(national_number, number.italian_leading_zero() ? "0" : "");
2140 StrAppend(national_number, number.national_number());
2143 int PhoneNumberUtil::GetLengthOfGeographicalAreaCode(
2144 const PhoneNumber& number) const {
2146 GetRegionCodeForNumber(number, ®ion_code);
2147 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2151 // If a country doesn't use a national prefix, and this number doesn't have an
2152 // Italian leading zero, we assume it is a closed dialling plan with no area
2154 if (!metadata->has_national_prefix() && !number.italian_leading_zero()) {
2158 if (!IsNumberGeographical(number)) {
2162 return GetLengthOfNationalDestinationCode(number);
2165 int PhoneNumberUtil::GetLengthOfNationalDestinationCode(
2166 const PhoneNumber& number) const {
2167 PhoneNumber copied_proto(number);
2168 if (number.has_extension()) {
2169 // Clear the extension so it's not included when formatting.
2170 copied_proto.clear_extension();
2173 string formatted_number;
2174 Format(copied_proto, INTERNATIONAL, &formatted_number);
2175 const scoped_ptr<RegExpInput> i18n_number(
2176 reg_exps_->regexp_factory_->CreateInput(formatted_number));
2180 for (int i = 0; i < 3; ++i) {
2181 if (!reg_exps_->capturing_ascii_digits_pattern_->FindAndConsume(
2182 i18n_number.get(), &digit_group)) {
2183 // We should find at least three groups.
2188 } else if (i == 2) {
2189 third_group = digit_group;
2193 GetRegionCodeForCountryCode(number.country_code(), ®ion_code);
2194 if (region_code == "AR" &&
2195 GetNumberType(number) == MOBILE) {
2196 // Argentinian mobile numbers, when formatted in the international format,
2197 // are in the form of +54 9 NDC XXXX.... As a result, we take the length of
2198 // the third group (NDC) and add 1 for the digit 9, which also forms part of
2199 // the national significant number.
2200 return third_group.size() + 1;
2205 void PhoneNumberUtil::NormalizeDigitsOnly(string* number) const {
2207 const RegExp& non_digits_pattern = reg_exps_->regexp_cache_->GetRegExp(
2208 StrCat("[^", kDigits, "]"));
2209 // Delete everything that isn't valid digits.
2210 non_digits_pattern.GlobalReplace(number, "");
2211 // Normalize all decimal digits to ASCII digits.
2212 number->assign(NormalizeUTF8::NormalizeDecimalDigits(*number));
2215 bool PhoneNumberUtil::IsAlphaNumber(const string& number) const {
2216 if (!IsViablePhoneNumber(number)) {
2217 // Number is too short, or doesn't match the basic phone number pattern.
2220 // Copy the number, since we are going to try and strip the extension from it.
2221 string number_copy(number);
2223 MaybeStripExtension(&number_copy, &extension);
2224 return reg_exps_->valid_alpha_phone_pattern_->FullMatch(number_copy);
2227 void PhoneNumberUtil::ConvertAlphaCharactersInNumber(string* number) const {
2229 NormalizeHelper(reg_exps_->alpha_phone_mappings_, false, number);
2232 // Normalizes a string of characters representing a phone number. This performs
2233 // the following conversions:
2234 // - Punctuation is stripped.
2235 // For ALPHA/VANITY numbers:
2236 // - Letters are converted to their numeric representation on a telephone
2237 // keypad. The keypad used here is the one defined in ITU Recommendation
2238 // E.161. This is only done if there are 3 or more letters in the number, to
2239 // lessen the risk that such letters are typos.
2240 // For other numbers:
2241 // - Wide-ascii digits are converted to normal ASCII (European) digits.
2242 // - Arabic-Indic numerals are converted to European numerals.
2243 // - Spurious alpha characters are stripped.
2244 void PhoneNumberUtil::Normalize(string* number) const {
2246 if (reg_exps_->valid_alpha_phone_pattern_->PartialMatch(*number)) {
2247 NormalizeHelper(reg_exps_->alpha_phone_mappings_, true, number);
2249 NormalizeDigitsOnly(number);
2252 // Checks to see if the string of characters could possibly be a phone number at
2253 // all. At the moment, checks to see that the string begins with at least 3
2254 // digits, ignoring any punctuation commonly found in phone numbers. This
2255 // method does not require the number to be normalized in advance - but does
2256 // assume that leading non-number symbols have been removed, such as by the
2257 // method ExtractPossibleNumber.
2258 bool PhoneNumberUtil::IsViablePhoneNumber(const string& number) const {
2259 if (number.length() < kMinLengthForNsn) {
2260 VLOG(2) << "Number too short to be viable:" << number;
2263 return reg_exps_->valid_phone_number_pattern_->FullMatch(number);
2266 // Strips the IDD from the start of the number if present. Helper function used
2267 // by MaybeStripInternationalPrefixAndNormalize.
2268 bool PhoneNumberUtil::ParsePrefixAsIdd(const RegExp& idd_pattern,
2269 string* number) const {
2271 const scoped_ptr<RegExpInput> number_copy(
2272 reg_exps_->regexp_factory_->CreateInput(*number));
2273 // First attempt to strip the idd_pattern at the start, if present. We make a
2274 // copy so that we can revert to the original string if necessary.
2275 if (idd_pattern.Consume(number_copy.get())) {
2276 // Only strip this if the first digit after the match is not a 0, since
2277 // country calling codes cannot begin with 0.
2278 string extracted_digit;
2279 if (reg_exps_->capturing_digit_pattern_->PartialMatch(
2280 number_copy->ToString(), &extracted_digit)) {
2281 NormalizeDigitsOnly(&extracted_digit);
2282 if (extracted_digit == "0") {
2286 number->assign(number_copy->ToString());
2292 // Strips any international prefix (such as +, 00, 011) present in the number
2293 // provided, normalizes the resulting number, and indicates if an international
2294 // prefix was present.
2296 // possible_idd_prefix represents the international direct dialing prefix from
2297 // the region we think this number may be dialed in.
2298 // Returns true if an international dialing prefix could be removed from the
2299 // number, otherwise false if the number did not seem to be in international
2301 PhoneNumber::CountryCodeSource
2302 PhoneNumberUtil::MaybeStripInternationalPrefixAndNormalize(
2303 const string& possible_idd_prefix,
2304 string* number) const {
2306 if (number->empty()) {
2307 return PhoneNumber::FROM_DEFAULT_COUNTRY;
2309 const scoped_ptr<RegExpInput> number_string_piece(
2310 reg_exps_->regexp_factory_->CreateInput(*number));
2311 if (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get())) {
2312 number->assign(number_string_piece->ToString());
2313 // Can now normalize the rest of the number since we've consumed the "+"
2314 // sign at the start.
2316 return PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN;
2318 // Attempt to parse the first digits as an international prefix.
2319 const RegExp& idd_pattern =
2320 reg_exps_->regexp_cache_->GetRegExp(possible_idd_prefix);
2322 return ParsePrefixAsIdd(idd_pattern, number)
2323 ? PhoneNumber::FROM_NUMBER_WITH_IDD
2324 : PhoneNumber::FROM_DEFAULT_COUNTRY;
2327 // Strips any national prefix (such as 0, 1) present in the number provided.
2328 // The number passed in should be the normalized telephone number that we wish
2329 // to strip any national dialing prefix from. The metadata should be for the
2330 // region that we think this number is from. Returns true if a national prefix
2331 // and/or carrier code was stripped.
2332 bool PhoneNumberUtil::MaybeStripNationalPrefixAndCarrierCode(
2333 const PhoneMetadata& metadata,
2335 string* carrier_code) const {
2337 string carrier_code_temp;
2338 const string& possible_national_prefix =
2339 metadata.national_prefix_for_parsing();
2340 if (number->empty() || possible_national_prefix.empty()) {
2341 // Early return for numbers of zero length or with no national prefix
2345 // We use two copies here since Consume modifies the phone number, and if the
2346 // first if-clause fails the number will already be changed.
2347 const scoped_ptr<RegExpInput> number_copy(
2348 reg_exps_->regexp_factory_->CreateInput(*number));
2349 const scoped_ptr<RegExpInput> number_copy_without_transform(
2350 reg_exps_->regexp_factory_->CreateInput(*number));
2351 string number_string_copy(*number);
2352 string captured_part_of_prefix;
2353 const RegExp& national_number_rule = reg_exps_->regexp_cache_->GetRegExp(
2354 metadata.general_desc().national_number_pattern());
2355 // Check if the original number is viable.
2356 bool is_viable_original_number = national_number_rule.FullMatch(*number);
2357 // Attempt to parse the first digits as a national prefix. We make a
2358 // copy so that we can revert to the original string if necessary.
2359 const string& transform_rule = metadata.national_prefix_transform_rule();
2360 const RegExp& possible_national_prefix_pattern =
2361 reg_exps_->regexp_cache_->GetRegExp(possible_national_prefix);
2362 if (!transform_rule.empty() &&
2363 (possible_national_prefix_pattern.Consume(
2364 number_copy.get(), &carrier_code_temp, &captured_part_of_prefix) ||
2365 possible_national_prefix_pattern.Consume(
2366 number_copy.get(), &captured_part_of_prefix)) &&
2367 !captured_part_of_prefix.empty()) {
2368 // If this succeeded, then we must have had a transform rule and there must
2369 // have been some part of the prefix that we captured.
2370 // We make the transformation and check that the resultant number is still
2371 // viable. If so, replace the number and return.
2372 possible_national_prefix_pattern.Replace(&number_string_copy,
2374 if (is_viable_original_number &&
2375 !national_number_rule.FullMatch(number_string_copy)) {
2378 number->assign(number_string_copy);
2380 carrier_code->assign(carrier_code_temp);
2382 } else if (possible_national_prefix_pattern.Consume(
2383 number_copy_without_transform.get(), &carrier_code_temp) ||
2384 possible_national_prefix_pattern.Consume(
2385 number_copy_without_transform.get())) {
2386 VLOG(4) << "Parsed the first digits as a national prefix.";
2387 // If captured_part_of_prefix is empty, this implies nothing was captured by
2388 // the capturing groups in possible_national_prefix; therefore, no
2389 // transformation is necessary, and we just remove the national prefix.
2390 const string number_copy_as_string =
2391 number_copy_without_transform->ToString();
2392 if (is_viable_original_number &&
2393 !national_number_rule.FullMatch(number_copy_as_string)) {
2396 number->assign(number_copy_as_string);
2398 carrier_code->assign(carrier_code_temp);
2402 VLOG(4) << "The first digits did not match the national prefix.";
2407 // Strips any extension (as in, the part of the number dialled after the call is
2408 // connected, usually indicated with extn, ext, x or similar) from the end of
2409 // the number, and returns it. The number passed in should be non-normalized.
2410 bool PhoneNumberUtil::MaybeStripExtension(string* number, string* extension)
2414 // There are three extension capturing groups in the regular expression.
2415 string possible_extension_one;
2416 string possible_extension_two;
2417 string possible_extension_three;
2418 string number_copy(*number);
2419 const scoped_ptr<RegExpInput> number_copy_as_regexp_input(
2420 reg_exps_->regexp_factory_->CreateInput(number_copy));
2421 if (reg_exps_->extn_pattern_->Consume(number_copy_as_regexp_input.get(),
2423 &possible_extension_one,
2424 &possible_extension_two,
2425 &possible_extension_three)) {
2426 // Replace the extensions in the original string here.
2427 reg_exps_->extn_pattern_->Replace(&number_copy, "");
2428 VLOG(4) << "Found an extension. Possible extension one: "
2429 << possible_extension_one
2430 << ". Possible extension two: " << possible_extension_two
2431 << ". Possible extension three: " << possible_extension_three
2432 << ". Remaining number: " << number_copy;
2433 // If we find a potential extension, and the number preceding this is a
2434 // viable number, we assume it is an extension.
2435 if ((!possible_extension_one.empty() || !possible_extension_two.empty() ||
2436 !possible_extension_three.empty()) &&
2437 IsViablePhoneNumber(number_copy)) {
2438 number->assign(number_copy);
2439 if (!possible_extension_one.empty()) {
2440 extension->assign(possible_extension_one);
2441 } else if (!possible_extension_two.empty()) {
2442 extension->assign(possible_extension_two);
2443 } else if (!possible_extension_three.empty()) {
2444 extension->assign(possible_extension_three);
2452 // Extracts country calling code from national_number, and returns it. It
2453 // assumes that the leading plus sign or IDD has already been removed. Returns 0
2454 // if national_number doesn't start with a valid country calling code, and
2455 // leaves national_number unmodified. Assumes the national_number is at least 3
2457 int PhoneNumberUtil::ExtractCountryCode(string* national_number) const {
2458 int potential_country_code;
2459 if (national_number->empty() || (national_number->at(0) == '0')) {
2460 // Country codes do not begin with a '0'.
2463 for (size_t i = 1; i <= kMaxLengthCountryCode; ++i) {
2464 safe_strto32(national_number->substr(0, i), &potential_country_code);
2466 GetRegionCodeForCountryCode(potential_country_code, ®ion_code);
2467 if (region_code != RegionCode::GetUnknown()) {
2468 national_number->erase(0, i);
2469 return potential_country_code;
2475 // Tries to extract a country calling code from a number. Country calling codes
2476 // are extracted in the following ways:
2477 // - by stripping the international dialing prefix of the region the person
2478 // is dialing from, if this is present in the number, and looking at the next
2480 // - by stripping the '+' sign if present and then looking at the next digits
2481 // - by comparing the start of the number and the country calling code of the
2482 // default region. If the number is not considered possible for the numbering
2483 // plan of the default region initially, but starts with the country calling
2484 // code of this region, validation will be reattempted after stripping this
2485 // country calling code. If this number is considered a possible number, then
2486 // the first digits will be considered the country calling code and removed as
2489 // Returns NO_PARSING_ERROR if a country calling code was successfully
2490 // extracted or none was present, or the appropriate error otherwise, such as
2491 // if a + was present but it was not followed by a valid country calling code.
2492 // If NO_PARSING_ERROR is returned, the national_number without the country
2493 // calling code is populated, and the country_code of the phone_number passed
2494 // in is set to the country calling code if found, otherwise to 0.
2495 PhoneNumberUtil::ErrorType PhoneNumberUtil::MaybeExtractCountryCode(
2496 const PhoneMetadata* default_region_metadata,
2497 bool keep_raw_input,
2498 string* national_number,
2499 PhoneNumber* phone_number) const {
2500 DCHECK(national_number);
2501 DCHECK(phone_number);
2502 // Set the default prefix to be something that will never match if there is no
2504 string possible_country_idd_prefix = default_region_metadata
2505 ? default_region_metadata->international_prefix()
2507 PhoneNumber::CountryCodeSource country_code_source =
2508 MaybeStripInternationalPrefixAndNormalize(possible_country_idd_prefix,
2510 if (keep_raw_input) {
2511 phone_number->set_country_code_source(country_code_source);
2513 if (country_code_source != PhoneNumber::FROM_DEFAULT_COUNTRY) {
2514 if (national_number->length() <= kMinLengthForNsn) {
2515 VLOG(2) << "Phone number had an IDD, but after this was not "
2516 << "long enough to be a viable phone number.";
2517 return TOO_SHORT_AFTER_IDD;
2519 int potential_country_code = ExtractCountryCode(national_number);
2520 if (potential_country_code != 0) {
2521 phone_number->set_country_code(potential_country_code);
2522 return NO_PARSING_ERROR;
2524 // If this fails, they must be using a strange country calling code that we
2525 // don't recognize, or that doesn't exist.
2526 return INVALID_COUNTRY_CODE_ERROR;
2527 } else if (default_region_metadata) {
2528 // Check to see if the number starts with the country calling code for the
2529 // default region. If so, we remove the country calling code, and do some
2530 // checks on the validity of the number before and after.
2531 int default_country_code = default_region_metadata->country_code();
2532 string default_country_code_string(SimpleItoa(default_country_code));
2533 VLOG(4) << "Possible country calling code: " << default_country_code_string;
2534 string potential_national_number;
2535 if (TryStripPrefixString(*national_number,
2536 default_country_code_string,
2537 &potential_national_number)) {
2538 const PhoneNumberDesc& general_num_desc =
2539 default_region_metadata->general_desc();
2540 const RegExp& valid_number_pattern =
2541 reg_exps_->regexp_cache_->GetRegExp(
2542 general_num_desc.national_number_pattern());
2543 MaybeStripNationalPrefixAndCarrierCode(*default_region_metadata,
2544 &potential_national_number,
2546 VLOG(4) << "Number without country calling code prefix: "
2547 << potential_national_number;
2548 const RegExp& possible_number_pattern =
2549 reg_exps_->regexp_cache_->GetRegExp(
2550 StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2551 // If the number was not valid before but is valid now, or if it was too
2552 // long before, we consider the number with the country code stripped to
2553 // be a better result and keep that instead.
2554 if ((!valid_number_pattern.FullMatch(*national_number) &&
2555 valid_number_pattern.FullMatch(potential_national_number)) ||
2556 TestNumberLengthAgainstPattern(possible_number_pattern,
2557 *national_number) == TOO_LONG) {
2558 national_number->assign(potential_national_number);
2559 if (keep_raw_input) {
2560 phone_number->set_country_code_source(
2561 PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN);
2563 phone_number->set_country_code(default_country_code);
2564 return NO_PARSING_ERROR;
2568 // No country calling code present. Set the country_code to 0.
2569 phone_number->set_country_code(0);
2570 return NO_PARSING_ERROR;
2573 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatch(
2574 const PhoneNumber& first_number_in,
2575 const PhoneNumber& second_number_in) const {
2576 // Make copies of the phone number so that the numbers passed in are not
2578 PhoneNumber first_number(first_number_in);
2579 PhoneNumber second_number(second_number_in);
2580 // First clear raw_input and country_code_source and
2581 // preferred_domestic_carrier_code fields and any empty-string extensions so
2582 // that we can use the proto-buffer equality method.
2583 first_number.clear_raw_input();
2584 first_number.clear_country_code_source();
2585 first_number.clear_preferred_domestic_carrier_code();
2586 second_number.clear_raw_input();
2587 second_number.clear_country_code_source();
2588 second_number.clear_preferred_domestic_carrier_code();
2589 if (first_number.extension().empty()) {
2590 first_number.clear_extension();
2592 if (second_number.extension().empty()) {
2593 second_number.clear_extension();
2595 // Early exit if both had extensions and these are different.
2596 if (first_number.has_extension() && second_number.has_extension() &&
2597 first_number.extension() != second_number.extension()) {
2600 int first_number_country_code = first_number.country_code();
2601 int second_number_country_code = second_number.country_code();
2602 // Both had country calling code specified.
2603 if (first_number_country_code != 0 && second_number_country_code != 0) {
2604 if (ExactlySameAs(first_number, second_number)) {
2606 } else if (first_number_country_code == second_number_country_code &&
2607 IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2608 // A SHORT_NSN_MATCH occurs if there is a difference because of the
2609 // presence or absence of an 'Italian leading zero', the presence or
2610 // absence of an extension, or one NSN being a shorter variant of the
2612 return SHORT_NSN_MATCH;
2614 // This is not a match.
2617 // Checks cases where one or both country calling codes were not specified. To
2618 // make equality checks easier, we first set the country_code fields to be
2620 first_number.set_country_code(second_number_country_code);
2621 // If all else was the same, then this is an NSN_MATCH.
2622 if (ExactlySameAs(first_number, second_number)) {
2625 if (IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2626 return SHORT_NSN_MATCH;
2631 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithTwoStrings(
2632 const string& first_number,
2633 const string& second_number) const {
2634 PhoneNumber first_number_as_proto;
2635 ErrorType error_type =
2636 Parse(first_number, RegionCode::GetUnknown(), &first_number_as_proto);
2637 if (error_type == NO_PARSING_ERROR) {
2638 return IsNumberMatchWithOneString(first_number_as_proto, second_number);
2640 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2641 PhoneNumber second_number_as_proto;
2642 ErrorType error_type = Parse(second_number, RegionCode::GetUnknown(),
2643 &second_number_as_proto);
2644 if (error_type == NO_PARSING_ERROR) {
2645 return IsNumberMatchWithOneString(second_number_as_proto, first_number);
2647 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2648 error_type = ParseHelper(first_number, RegionCode::GetUnknown(), false,
2649 false, &first_number_as_proto);
2650 if (error_type == NO_PARSING_ERROR) {
2651 error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2652 false, &second_number_as_proto);
2653 if (error_type == NO_PARSING_ERROR) {
2654 return IsNumberMatch(first_number_as_proto, second_number_as_proto);
2659 // One or more of the phone numbers we are trying to match is not a viable
2661 return INVALID_NUMBER;
2664 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithOneString(
2665 const PhoneNumber& first_number,
2666 const string& second_number) const {
2667 // First see if the second number has an implicit country calling code, by
2668 // attempting to parse it.
2669 PhoneNumber second_number_as_proto;
2670 ErrorType error_type =
2671 Parse(second_number, RegionCode::GetUnknown(), &second_number_as_proto);
2672 if (error_type == NO_PARSING_ERROR) {
2673 return IsNumberMatch(first_number, second_number_as_proto);
2675 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2676 // The second number has no country calling code. EXACT_MATCH is no longer
2677 // possible. We parse it as if the region was the same as that for the
2678 // first number, and if EXACT_MATCH is returned, we replace this with
2680 string first_number_region;
2681 GetRegionCodeForCountryCode(first_number.country_code(),
2682 &first_number_region);
2683 if (first_number_region != RegionCode::GetUnknown()) {
2684 PhoneNumber second_number_with_first_number_region;
2685 Parse(second_number, first_number_region,
2686 &second_number_with_first_number_region);
2687 MatchType match = IsNumberMatch(first_number,
2688 second_number_with_first_number_region);
2689 if (match == EXACT_MATCH) {
2694 // If the first number didn't have a valid country calling code, then we
2695 // parse the second number without one as well.
2696 error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2697 false, &second_number_as_proto);
2698 if (error_type == NO_PARSING_ERROR) {
2699 return IsNumberMatch(first_number, second_number_as_proto);
2703 // One or more of the phone numbers we are trying to match is not a viable
2705 return INVALID_NUMBER;
2708 AsYouTypeFormatter* PhoneNumberUtil::GetAsYouTypeFormatter(
2709 const string& region_code) const {
2710 return new AsYouTypeFormatter(region_code);
2713 bool PhoneNumberUtil::CanBeInternationallyDialled(
2714 const PhoneNumber& number) const {
2716 GetRegionCodeForNumber(number, ®ion_code);
2717 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2719 // Note numbers belonging to non-geographical entities (e.g. +800 numbers)
2720 // are always internationally diallable, and will be caught here.
2723 string national_significant_number;
2724 GetNationalSignificantNumber(number, &national_significant_number);
2725 return !IsNumberMatchingDesc(
2726 national_significant_number, metadata->no_international_dialling(),
2727 reg_exps_->regexp_cache_.get());
2730 } // namespace phonenumbers