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::set_logger_impl(logger);
375 class PhoneNumberRegExpsAndMappings {
377 void InitializeMapsAndSets() {
378 diallable_char_mappings_.insert(make_pair('+', '+'));
379 diallable_char_mappings_.insert(make_pair('*', '*'));
380 // Here we insert all punctuation symbols that we wish to respect when
381 // formatting alpha numbers, as they show the intended number groupings.
382 all_plus_number_grouping_symbols_.insert(
383 make_pair(ToUnicodeCodepoint("-"), '-'));
384 all_plus_number_grouping_symbols_.insert(
385 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8D" /* "-" */), '-'));
386 all_plus_number_grouping_symbols_.insert(
387 make_pair(ToUnicodeCodepoint("\xE2\x80\x90" /* "‐" */), '-'));
388 all_plus_number_grouping_symbols_.insert(
389 make_pair(ToUnicodeCodepoint("\xE2\x80\x91" /* "‑" */), '-'));
390 all_plus_number_grouping_symbols_.insert(
391 make_pair(ToUnicodeCodepoint("\xE2\x80\x92" /* "‒" */), '-'));
392 all_plus_number_grouping_symbols_.insert(
393 make_pair(ToUnicodeCodepoint("\xE2\x80\x93" /* "–" */), '-'));
394 all_plus_number_grouping_symbols_.insert(
395 make_pair(ToUnicodeCodepoint("\xE2\x80\x94" /* "—" */), '-'));
396 all_plus_number_grouping_symbols_.insert(
397 make_pair(ToUnicodeCodepoint("\xE2\x80\x95" /* "―" */), '-'));
398 all_plus_number_grouping_symbols_.insert(
399 make_pair(ToUnicodeCodepoint("\xE2\x88\x92" /* "−" */), '-'));
400 all_plus_number_grouping_symbols_.insert(
401 make_pair(ToUnicodeCodepoint("/"), '/'));
402 all_plus_number_grouping_symbols_.insert(
403 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8F" /* "/" */), '/'));
404 all_plus_number_grouping_symbols_.insert(
405 make_pair(ToUnicodeCodepoint(" "), ' '));
406 all_plus_number_grouping_symbols_.insert(
407 make_pair(ToUnicodeCodepoint("\xE3\x80\x80" /* " " */), ' '));
408 all_plus_number_grouping_symbols_.insert(
409 make_pair(ToUnicodeCodepoint("\xE2\x81\xA0"), ' '));
410 all_plus_number_grouping_symbols_.insert(
411 make_pair(ToUnicodeCodepoint("."), '.'));
412 all_plus_number_grouping_symbols_.insert(
413 make_pair(ToUnicodeCodepoint("\xEF\xBC\x8E" /* "." */), '.'));
414 // Only the upper-case letters are added here - the lower-case versions are
415 // added programmatically.
416 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("A"), '2'));
417 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("B"), '2'));
418 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("C"), '2'));
419 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("D"), '3'));
420 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("E"), '3'));
421 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("F"), '3'));
422 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("G"), '4'));
423 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("H"), '4'));
424 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("I"), '4'));
425 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("J"), '5'));
426 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("K"), '5'));
427 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("L"), '5'));
428 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("M"), '6'));
429 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("N"), '6'));
430 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("O"), '6'));
431 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("P"), '7'));
432 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Q"), '7'));
433 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("R"), '7'));
434 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("S"), '7'));
435 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("T"), '8'));
436 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("U"), '8'));
437 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("V"), '8'));
438 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("W"), '9'));
439 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("X"), '9'));
440 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Y"), '9'));
441 alpha_mappings_.insert(make_pair(ToUnicodeCodepoint("Z"), '9'));
442 map<char32, char> lower_case_mappings;
443 map<char32, char> alpha_letters;
444 for (map<char32, char>::const_iterator it = alpha_mappings_.begin();
445 it != alpha_mappings_.end();
447 // Convert all the upper-case ASCII letters to lower-case.
448 if (it->first < 128) {
449 char letter_as_upper = static_cast<char>(it->first);
450 char32 letter_as_lower = static_cast<char32>(tolower(letter_as_upper));
451 lower_case_mappings.insert(make_pair(letter_as_lower, it->second));
452 // Add the letters in both variants to the alpha_letters map. This just
453 // pairs each letter with its upper-case representation so that it can
454 // be retained when normalising alpha numbers.
455 alpha_letters.insert(make_pair(letter_as_lower, letter_as_upper));
456 alpha_letters.insert(make_pair(it->first, letter_as_upper));
459 // In the Java version we don't insert the lower-case mappings in the map,
460 // because we convert to upper case on the fly. Doing this here would
461 // involve pulling in all of ICU, which we don't want to do if we don't have
463 alpha_mappings_.insert(lower_case_mappings.begin(),
464 lower_case_mappings.end());
465 alpha_phone_mappings_.insert(alpha_mappings_.begin(),
466 alpha_mappings_.end());
467 all_plus_number_grouping_symbols_.insert(alpha_letters.begin(),
468 alpha_letters.end());
469 // Add the ASCII digits so that they don't get deleted by NormalizeHelper().
470 for (char c = '0'; c <= '9'; ++c) {
471 diallable_char_mappings_.insert(make_pair(c, c));
472 alpha_phone_mappings_.insert(make_pair(c, c));
473 all_plus_number_grouping_symbols_.insert(make_pair(c, c));
477 // Small string helpers since StrCat has a maximum number of arguments. These
478 // are both used to build valid_phone_number_.
479 const string punctuation_and_star_sign_;
480 const string min_length_phone_number_pattern_;
482 // Regular expression of viable phone numbers. This is location independent.
483 // Checks we have at least three leading digits, and only valid punctuation,
484 // alpha characters and digits in the phone number. Does not include extension
485 // data. The symbol 'x' is allowed here as valid punctuation since it is often
486 // used as a placeholder for carrier codes, for example in Brazilian phone
487 // numbers. We also allow multiple plus-signs at the start.
488 // Corresponds to the following:
489 // [digits]{minLengthNsn}|
490 // plus_sign*(([punctuation]|[star])*[digits]){3,}
491 // ([punctuation]|[star]|[digits]|[alpha])*
493 // The first reg-ex is to allow short numbers (two digits long) to be parsed
494 // if they are entered as "15" etc, but only if there is no punctuation in
495 // them. The second expression restricts the number of digits to three or
496 // more, but then allows them to be in international form, and to have
497 // alpha-characters and punctuation.
498 const string valid_phone_number_;
500 // Regexp of all possible ways to write extensions, for use when parsing. This
501 // will be run as a case-insensitive regexp match. Wide character versions are
502 // also provided after each ASCII version.
503 // For parsing, we are slightly more lenient in our interpretation than for
504 // matching. Here we allow a "comma" as a possible extension indicator. When
505 // matching, this is hardly ever used to indicate this.
506 const string extn_patterns_for_parsing_;
509 scoped_ptr<const AbstractRegExpFactory> regexp_factory_;
510 scoped_ptr<RegExpCache> regexp_cache_;
512 // A map that contains characters that are essential when dialling. That means
513 // any of the characters in this map must not be removed from a number when
514 // dialing, otherwise the call will not reach the intended destination.
515 map<char32, char> diallable_char_mappings_;
516 // These mappings map a character (key) to a specific digit that should
517 // replace it for normalization purposes.
518 map<char32, char> alpha_mappings_;
519 // For performance reasons, store a map of combining alpha_mappings with ASCII
521 map<char32, char> alpha_phone_mappings_;
523 // Separate map of all symbols that we wish to retain when formatting alpha
524 // numbers. This includes digits, ascii letters and number grouping symbols
525 // such as "-" and " ".
526 map<char32, char> all_plus_number_grouping_symbols_;
528 // Pattern that makes it easy to distinguish whether a region has a unique
529 // international dialing prefix or not. If a region has a unique international
530 // prefix (e.g. 011 in USA), it will be represented as a string that contains
531 // a sequence of ASCII digits. If there are multiple available international
532 // prefixes in a region, they will be represented as a regex string that
533 // always contains character(s) other than ASCII digits.
534 // Note this regex also includes tilde, which signals waiting for the tone.
535 scoped_ptr<const RegExp> unique_international_prefix_;
537 scoped_ptr<const RegExp> digits_pattern_;
538 scoped_ptr<const RegExp> capturing_digit_pattern_;
539 scoped_ptr<const RegExp> capturing_ascii_digits_pattern_;
541 // Regular expression of acceptable characters that may start a phone number
542 // for the purposes of parsing. This allows us to strip away meaningless
543 // prefixes to phone numbers that may be mistakenly given to us. This consists
544 // of digits, the plus symbol and arabic-indic digits. This does not contain
545 // alpha characters, although they may be used later in the number. It also
546 // does not include other punctuation, as this will be stripped later during
547 // parsing and is of no information value when parsing a number. The string
548 // starting with this valid character is captured.
549 // This corresponds to VALID_START_CHAR in the java version.
550 scoped_ptr<const RegExp> valid_start_char_pattern_;
552 // Regular expression of valid characters before a marker that might indicate
554 scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_;
556 // Regular expression of trailing characters that we want to remove. We remove
557 // all characters that are not alpha or numerical characters. The hash
558 // character is retained here, as it may signify the previous block was an
559 // extension. Note the capturing block at the start to capture the rest of the
560 // number if this was a match.
561 // This corresponds to UNWANTED_END_CHAR_PATTERN in the java version.
562 scoped_ptr<const RegExp> unwanted_end_char_pattern_;
564 // Regular expression of groups of valid punctuation characters.
565 scoped_ptr<const RegExp> separator_pattern_;
567 // Regexp of all possible ways to write extensions, for use when finding phone
568 // numbers in text. This will be run as a case-insensitive regexp match. Wide
569 // character versions are also provided after each ASCII version.
570 const string extn_patterns_for_matching_;
572 // Regexp of all known extension prefixes used by different regions followed
573 // by 1 or more valid digits, for use when parsing.
574 scoped_ptr<const RegExp> extn_pattern_;
576 // We append optionally the extension pattern to the end here, as a valid
577 // phone number may have an extension prefix appended, followed by 1 or more
579 scoped_ptr<const RegExp> valid_phone_number_pattern_;
581 // We use this pattern to check if the phone number has at least three letters
582 // in it - if so, then we treat it as a number where some phone-number digits
583 // are represented by letters.
584 scoped_ptr<const RegExp> valid_alpha_phone_pattern_;
586 scoped_ptr<const RegExp> first_group_capturing_pattern_;
588 scoped_ptr<const RegExp> carrier_code_pattern_;
590 scoped_ptr<const RegExp> plus_chars_pattern_;
592 PhoneNumberRegExpsAndMappings()
593 : punctuation_and_star_sign_(StrCat(PhoneNumberUtil::kValidPunctuation,
595 min_length_phone_number_pattern_(
596 StrCat(kDigits, "{", PhoneNumberUtil::kMinLengthForNsn, "}")),
598 StrCat(min_length_phone_number_pattern_, "|[",
599 PhoneNumberUtil::kPlusChars, "]*(?:[",
600 punctuation_and_star_sign_, "]*",
601 kDigits, "){3,}[", kValidAlpha,
602 punctuation_and_star_sign_, kDigits,
604 extn_patterns_for_parsing_(
605 CreateExtnPattern(StrCat(",", kSingleExtnSymbolsForMatching))),
606 regexp_factory_(new RegExpFactory()),
607 regexp_cache_(new RegExpCache(*regexp_factory_.get(), 128)),
608 diallable_char_mappings_(),
610 alpha_phone_mappings_(),
611 all_plus_number_grouping_symbols_(),
612 unique_international_prefix_(regexp_factory_->CreateRegExp(
613 /* "[\\d]+(?:[~⁓∼~][\\d]+)?" */
614 "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?")),
616 regexp_factory_->CreateRegExp(StrCat("[", kDigits, "]*"))),
617 capturing_digit_pattern_(
618 regexp_factory_->CreateRegExp(StrCat("([", kDigits, "])"))),
619 capturing_ascii_digits_pattern_(
620 regexp_factory_->CreateRegExp("(\\d+)")),
621 valid_start_char_pattern_(regexp_factory_->CreateRegExp(
622 StrCat("[", PhoneNumberUtil::kPlusChars, kDigits, "]"))),
623 capture_up_to_second_number_start_pattern_(
624 regexp_factory_->CreateRegExp(
625 PhoneNumberUtil::kCaptureUpToSecondNumberStart)),
626 unwanted_end_char_pattern_(
627 regexp_factory_->CreateRegExp("[^\\p{N}\\p{L}#]")),
629 regexp_factory_->CreateRegExp(
630 StrCat("[", PhoneNumberUtil::kValidPunctuation, "]+"))),
631 extn_patterns_for_matching_(
632 CreateExtnPattern(kSingleExtnSymbolsForMatching)),
633 extn_pattern_(regexp_factory_->CreateRegExp(
634 StrCat("(?i)(?:", extn_patterns_for_parsing_, ")$"))),
635 valid_phone_number_pattern_(regexp_factory_->CreateRegExp(
636 StrCat("(?i)", valid_phone_number_,
637 "(?:", extn_patterns_for_parsing_, ")?"))),
638 valid_alpha_phone_pattern_(regexp_factory_->CreateRegExp(
639 StrCat("(?i)(?:.*?[", kValidAlpha, "]){3}"))),
640 // The first_group_capturing_pattern was originally set to $1 but there
641 // are some countries for which the first group is not used in the
642 // national pattern (e.g. Argentina) so the $1 group does not match
643 // correctly. Therefore, we use \d, so that the first group actually
644 // used in the pattern will be matched.
645 first_group_capturing_pattern_(
646 regexp_factory_->CreateRegExp("(\\$\\d)")),
647 carrier_code_pattern_(regexp_factory_->CreateRegExp("\\$CC")),
649 regexp_factory_->CreateRegExp(
650 StrCat("[", PhoneNumberUtil::kPlusChars, "]+"))) {
651 InitializeMapsAndSets();
655 DISALLOW_COPY_AND_ASSIGN(PhoneNumberRegExpsAndMappings);
658 // Private constructor. Also takes care of initialisation.
659 PhoneNumberUtil::PhoneNumberUtil()
660 : logger_(Logger::set_logger_impl(new StdoutLogger())),
661 reg_exps_(new PhoneNumberRegExpsAndMappings),
662 country_calling_code_to_region_code_map_(new vector<IntRegionsPair>()),
663 nanpa_regions_(new set<string>()),
664 region_to_metadata_map_(new map<string, PhoneMetadata>()),
665 country_code_to_non_geographical_metadata_map_(
666 new map<int, PhoneMetadata>) {
667 Logger::set_logger_impl(logger_.get());
668 // TODO: Update the java version to put the contents of the init
669 // method inside the constructor as well to keep both in sync.
670 PhoneMetadataCollection metadata_collection;
671 if (!LoadCompiledInMetadata(&metadata_collection)) {
672 LOG(DFATAL) << "Could not parse compiled-in metadata.";
675 // Storing data in a temporary map to make it easier to find other regions
676 // that share a country calling code when inserting data.
677 map<int, list<string>* > country_calling_code_to_region_map;
678 for (RepeatedPtrField<PhoneMetadata>::const_iterator it =
679 metadata_collection.metadata().begin();
680 it != metadata_collection.metadata().end();
682 const string& region_code = it->id();
683 if (region_code == RegionCode::GetUnknown()) {
687 int country_calling_code = it->country_code();
688 if (kRegionCodeForNonGeoEntity == region_code) {
689 country_code_to_non_geographical_metadata_map_->insert(
690 make_pair(country_calling_code, *it));
692 region_to_metadata_map_->insert(make_pair(region_code, *it));
694 map<int, list<string>* >::iterator calling_code_in_map =
695 country_calling_code_to_region_map.find(country_calling_code);
696 if (calling_code_in_map != country_calling_code_to_region_map.end()) {
697 if (it->main_country_for_code()) {
698 calling_code_in_map->second->push_front(region_code);
700 calling_code_in_map->second->push_back(region_code);
703 // For most country calling codes, there will be only one region code.
704 list<string>* list_with_region_code = new list<string>();
705 list_with_region_code->push_back(region_code);
706 country_calling_code_to_region_map.insert(
707 make_pair(country_calling_code, list_with_region_code));
709 if (country_calling_code == kNanpaCountryCode) {
710 nanpa_regions_->insert(region_code);
714 country_calling_code_to_region_code_map_->insert(
715 country_calling_code_to_region_code_map_->begin(),
716 country_calling_code_to_region_map.begin(),
717 country_calling_code_to_region_map.end());
718 // Sort all the pairs in ascending order according to country calling code.
719 sort(country_calling_code_to_region_code_map_->begin(),
720 country_calling_code_to_region_code_map_->end(),
724 PhoneNumberUtil::~PhoneNumberUtil() {
725 STLDeleteContainerPairSecondPointers(
726 country_calling_code_to_region_code_map_->begin(),
727 country_calling_code_to_region_code_map_->end());
730 void PhoneNumberUtil::GetSupportedRegions(set<string>* regions) const {
732 for (map<string, PhoneMetadata>::const_iterator it =
733 region_to_metadata_map_->begin(); it != region_to_metadata_map_->end();
735 regions->insert(it->first);
739 // Public wrapper function to get a PhoneNumberUtil instance with the default
742 #ifdef USE_GOOGLE_BASE
743 PhoneNumberUtil* PhoneNumberUtil::GetInstance() {
744 return Singleton<PhoneNumberUtil>::get();
748 const string& PhoneNumberUtil::GetExtnPatternsForMatching() const {
749 return reg_exps_->extn_patterns_for_matching_;
752 bool PhoneNumberUtil::StartsWithPlusCharsPattern(const string& number)
754 const scoped_ptr<RegExpInput> number_string_piece(
755 reg_exps_->regexp_factory_->CreateInput(number));
756 return reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get());
759 bool PhoneNumberUtil::ContainsOnlyValidDigits(const string& s) const {
760 return reg_exps_->digits_pattern_->FullMatch(s);
763 void PhoneNumberUtil::TrimUnwantedEndChars(string* number) const {
765 UnicodeText number_as_unicode;
766 number_as_unicode.PointToUTF8(number->data(), number->size());
767 char current_char[5];
769 UnicodeText::const_reverse_iterator reverse_it(number_as_unicode.end());
770 for (; reverse_it.base() != number_as_unicode.begin(); ++reverse_it) {
771 len = reverse_it.get_utf8(current_char);
772 current_char[len] = '\0';
773 if (!reg_exps_->unwanted_end_char_pattern_->FullMatch(current_char)) {
778 number->assign(UnicodeText::UTF8Substring(number_as_unicode.begin(),
782 bool PhoneNumberUtil::IsFormatEligibleForAsYouTypeFormatter(
783 const string& format) const {
784 // A pattern that is used to determine if a numberFormat under
785 // availableFormats is eligible to be used by the AYTF. It is eligible when
786 // the format element under numberFormat contains groups of the dollar sign
787 // followed by a single digit, separated by valid phone number punctuation.
788 // This prevents invalid punctuation (such as the star sign in Israeli star
789 // numbers) getting into the output of the AYTF.
790 const RegExp& eligible_format_pattern = reg_exps_->regexp_cache_->GetRegExp(
791 StrCat("[", kValidPunctuation, "]*", "(\\$\\d", "[",
792 kValidPunctuation, "]*)+"));
793 return eligible_format_pattern.FullMatch(format);
796 bool PhoneNumberUtil::FormattingRuleHasFirstGroupOnly(
797 const string& national_prefix_formatting_rule) const {
798 // A pattern that is used to determine if the national prefix formatting rule
799 // has the first group only, i.e., does not start with the national prefix.
800 // Note that the pattern explicitly allows for unbalanced parentheses.
801 const RegExp& first_group_only_prefix_pattern =
802 reg_exps_->regexp_cache_->GetRegExp("\\(?\\$1\\)?");
803 return first_group_only_prefix_pattern.FullMatch(
804 national_prefix_formatting_rule);
807 void PhoneNumberUtil::GetNddPrefixForRegion(const string& region_code,
808 bool strip_non_digits,
809 string* national_prefix) const {
810 DCHECK(national_prefix);
811 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
813 LOG(WARNING) << "Invalid or unknown region code (" << region_code
817 national_prefix->assign(metadata->national_prefix());
818 if (strip_non_digits) {
819 // Note: if any other non-numeric symbols are ever used in national
820 // prefixes, these would have to be removed here as well.
821 strrmm(national_prefix, "~");
825 bool PhoneNumberUtil::IsValidRegionCode(const string& region_code) const {
826 return (region_to_metadata_map_->find(region_code) !=
827 region_to_metadata_map_->end());
830 bool PhoneNumberUtil::HasValidCountryCallingCode(
831 int country_calling_code) const {
832 // Create an IntRegionsPair with the country_code passed in, and use it to
833 // locate the pair with the same country_code in the sorted vector.
834 IntRegionsPair target_pair;
835 target_pair.first = country_calling_code;
836 return (binary_search(country_calling_code_to_region_code_map_->begin(),
837 country_calling_code_to_region_code_map_->end(),
838 target_pair, OrderByFirst()));
841 // Returns a pointer to the phone metadata for the appropriate region or NULL
842 // if the region code is invalid or unknown.
843 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegion(
844 const string& region_code) const {
845 map<string, PhoneMetadata>::const_iterator it =
846 region_to_metadata_map_->find(region_code);
847 if (it != region_to_metadata_map_->end()) {
853 const PhoneMetadata* PhoneNumberUtil::GetMetadataForNonGeographicalRegion(
854 int country_calling_code) const {
855 map<int, PhoneMetadata>::const_iterator it =
856 country_code_to_non_geographical_metadata_map_->find(
857 country_calling_code);
858 if (it != country_code_to_non_geographical_metadata_map_->end()) {
864 void PhoneNumberUtil::Format(const PhoneNumber& number,
865 PhoneNumberFormat number_format,
866 string* formatted_number) const {
867 DCHECK(formatted_number);
868 if (number.national_number() == 0) {
869 const string& raw_input = number.raw_input();
870 if (!raw_input.empty()) {
871 // Unparseable numbers that kept their raw input just use that.
872 // This is the only case where a number can be formatted as E164 without a
873 // leading '+' symbol (but the original number wasn't parseable anyway).
874 // TODO: Consider removing the 'if' above so that unparseable
875 // strings without raw input format to the empty string instead of "+00".
876 formatted_number->assign(raw_input);
880 int country_calling_code = number.country_code();
881 string national_significant_number;
882 GetNationalSignificantNumber(number, &national_significant_number);
883 if (number_format == E164) {
884 // Early exit for E164 case (even if the country calling code is invalid)
885 // since no formatting of the national number needs to be applied.
886 // Extensions are not formatted.
887 formatted_number->assign(national_significant_number);
888 PrefixNumberWithCountryCallingCode(country_calling_code, E164,
892 if (!HasValidCountryCallingCode(country_calling_code)) {
893 formatted_number->assign(national_significant_number);
896 // Note here that all NANPA formatting rules are contained by US, so we use
897 // that to format NANPA numbers. The same applies to Russian Fed regions -
898 // rules are contained by Russia. French Indian Ocean country rules are
899 // contained by Réunion.
901 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
902 // Metadata cannot be NULL because the country calling code is valid (which
903 // means that the region code cannot be ZZ and must be one of our supported
905 const PhoneMetadata* metadata =
906 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
907 FormatNsn(national_significant_number, *metadata, number_format,
909 MaybeAppendFormattedExtension(number, *metadata, number_format,
911 PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
915 void PhoneNumberUtil::FormatByPattern(
916 const PhoneNumber& number,
917 PhoneNumberFormat number_format,
918 const RepeatedPtrField<NumberFormat>& user_defined_formats,
919 string* formatted_number) const {
920 DCHECK(formatted_number);
921 int country_calling_code = number.country_code();
922 // Note GetRegionCodeForCountryCode() is used because formatting information
923 // for regions which share a country calling code is contained by only one
924 // region for performance reasons. For example, for NANPA regions it will be
925 // contained in the metadata for US.
926 string national_significant_number;
927 GetNationalSignificantNumber(number, &national_significant_number);
928 if (!HasValidCountryCallingCode(country_calling_code)) {
929 formatted_number->assign(national_significant_number);
933 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
934 // Metadata cannot be NULL because the country calling code is valid.
935 const PhoneMetadata* metadata =
936 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
937 const NumberFormat* formatting_pattern =
938 ChooseFormattingPatternForNumber(user_defined_formats,
939 national_significant_number);
940 if (!formatting_pattern) {
941 // If no pattern above is matched, we format the number as a whole.
942 formatted_number->assign(national_significant_number);
944 NumberFormat num_format_copy;
945 // Before we do a replacement of the national prefix pattern $NP with the
946 // national prefix, we need to copy the rule so that subsequent replacements
947 // for different numbers have the appropriate national prefix.
948 num_format_copy.MergeFrom(*formatting_pattern);
949 string national_prefix_formatting_rule(
950 formatting_pattern->national_prefix_formatting_rule());
951 if (!national_prefix_formatting_rule.empty()) {
952 const string& national_prefix = metadata->national_prefix();
953 if (!national_prefix.empty()) {
954 // Replace $NP with national prefix and $FG with the first group ($1).
955 GlobalReplaceSubstring("$NP", national_prefix,
956 &national_prefix_formatting_rule);
957 GlobalReplaceSubstring("$FG", "$1",
958 &national_prefix_formatting_rule);
959 num_format_copy.set_national_prefix_formatting_rule(
960 national_prefix_formatting_rule);
962 // We don't want to have a rule for how to format the national prefix if
964 num_format_copy.clear_national_prefix_formatting_rule();
967 FormatNsnUsingPattern(national_significant_number, num_format_copy,
968 number_format, formatted_number);
970 MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
971 PrefixNumberWithCountryCallingCode(country_calling_code, number_format,
975 void PhoneNumberUtil::FormatNationalNumberWithCarrierCode(
976 const PhoneNumber& number,
977 const string& carrier_code,
978 string* formatted_number) const {
979 int country_calling_code = number.country_code();
980 string national_significant_number;
981 GetNationalSignificantNumber(number, &national_significant_number);
982 if (!HasValidCountryCallingCode(country_calling_code)) {
983 formatted_number->assign(national_significant_number);
987 // Note GetRegionCodeForCountryCode() is used because formatting information
988 // for regions which share a country calling code is contained by only one
989 // region for performance reasons. For example, for NANPA regions it will be
990 // contained in the metadata for US.
992 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
993 // Metadata cannot be NULL because the country calling code is valid.
994 const PhoneMetadata* metadata =
995 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
996 FormatNsnWithCarrier(national_significant_number, *metadata, NATIONAL,
997 carrier_code, formatted_number);
998 MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number);
999 PrefixNumberWithCountryCallingCode(country_calling_code, NATIONAL,
1003 const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegionOrCallingCode(
1004 int country_calling_code, const string& region_code) const {
1005 return kRegionCodeForNonGeoEntity == region_code
1006 ? GetMetadataForNonGeographicalRegion(country_calling_code)
1007 : GetMetadataForRegion(region_code);
1010 void PhoneNumberUtil::FormatNationalNumberWithPreferredCarrierCode(
1011 const PhoneNumber& number,
1012 const string& fallback_carrier_code,
1013 string* formatted_number) const {
1014 FormatNationalNumberWithCarrierCode(
1016 number.has_preferred_domestic_carrier_code()
1017 ? number.preferred_domestic_carrier_code()
1018 : fallback_carrier_code,
1022 void PhoneNumberUtil::FormatNumberForMobileDialing(
1023 const PhoneNumber& number,
1024 const string& calling_from,
1025 bool with_formatting,
1026 string* formatted_number) const {
1027 int country_calling_code = number.country_code();
1028 if (!HasValidCountryCallingCode(country_calling_code)) {
1029 formatted_number->assign(number.has_raw_input() ? number.raw_input() : "");
1033 formatted_number->assign("");
1034 // Clear the extension, as that part cannot normally be dialed together with
1036 PhoneNumber number_no_extension(number);
1037 number_no_extension.clear_extension();
1039 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
1040 if (calling_from == region_code) {
1041 PhoneNumberType number_type = GetNumberType(number_no_extension);
1042 bool is_fixed_line_or_mobile =
1043 (number_type == FIXED_LINE) || (number_type == MOBILE) ||
1044 (number_type == FIXED_LINE_OR_MOBILE);
1045 // Carrier codes may be needed in some countries. We handle this here.
1046 if ((region_code == "CO") && (number_type == FIXED_LINE)) {
1047 FormatNationalNumberWithCarrierCode(
1048 number_no_extension, kColombiaMobileToFixedLinePrefix,
1050 } else if ((region_code == "BR") && (is_fixed_line_or_mobile)) {
1051 if (number_no_extension.has_preferred_domestic_carrier_code()) {
1052 FormatNationalNumberWithPreferredCarrierCode(number_no_extension, "",
1055 // Brazilian fixed line and mobile numbers need to be dialed with a
1056 // carrier code when called within Brazil. Without that, most of the
1057 // carriers won't connect the call. Because of that, we return an empty
1059 formatted_number->assign("");
1062 // For NANPA countries, non-geographical countries, and Mexican fixed line
1063 // and mobile numbers, we output international format for numbers that can
1064 // be dialed internationally as that always works.
1065 if ((country_calling_code == kNanpaCountryCode ||
1066 region_code == kRegionCodeForNonGeoEntity ||
1067 // MX fixed line and mobile numbers should always be formatted in
1068 // international format, even when dialed within MX. For national
1069 // format to work, a carrier code needs to be used, and the correct
1070 // carrier code depends on if the caller and callee are from the same
1071 // local area. It is trickier to get that to work correctly than
1072 // using international format, which is tested to work fine on all
1074 (region_code == "MX" && is_fixed_line_or_mobile)) &&
1075 CanBeInternationallyDialled(number_no_extension)) {
1076 Format(number_no_extension, INTERNATIONAL, formatted_number);
1078 Format(number_no_extension, NATIONAL, formatted_number);
1082 } else if (CanBeInternationallyDialled(number_no_extension)) {
1084 ? Format(number_no_extension, INTERNATIONAL, formatted_number)
1085 : Format(number_no_extension, E164, formatted_number);
1088 if (!with_formatting) {
1089 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1090 true /* remove non matches */, formatted_number);
1094 void PhoneNumberUtil::FormatOutOfCountryCallingNumber(
1095 const PhoneNumber& number,
1096 const string& calling_from,
1097 string* formatted_number) const {
1098 DCHECK(formatted_number);
1099 if (!IsValidRegionCode(calling_from)) {
1100 LOG(WARNING) << "Trying to format number from invalid region "
1102 << ". International formatting applied.";
1103 Format(number, INTERNATIONAL, formatted_number);
1106 int country_code = number.country_code();
1107 string national_significant_number;
1108 GetNationalSignificantNumber(number, &national_significant_number);
1109 if (!HasValidCountryCallingCode(country_code)) {
1110 formatted_number->assign(national_significant_number);
1113 if (country_code == kNanpaCountryCode) {
1114 if (IsNANPACountry(calling_from)) {
1115 // For NANPA regions, return the national format for these regions but
1116 // prefix it with the country calling code.
1117 Format(number, NATIONAL, formatted_number);
1118 formatted_number->insert(0, StrCat(country_code, " "));
1121 } else if (country_code == GetCountryCodeForValidRegion(calling_from)) {
1122 // If neither region is a NANPA region, then we check to see if the
1123 // country calling code of the number and the country calling code of the
1124 // region we are calling from are the same.
1125 // For regions that share a country calling code, the country calling code
1126 // need not be dialled. This also applies when dialling within a region, so
1127 // this if clause covers both these cases.
1128 // Technically this is the case for dialling from la Réunion to other
1129 // overseas departments of France (French Guiana, Martinique, Guadeloupe),
1130 // but not vice versa - so we don't cover this edge case for now and for
1131 // those cases return the version including country calling code.
1133 // http://www.petitfute.com/voyage/225-info-pratiques-reunion
1134 Format(number, NATIONAL, formatted_number);
1137 // Metadata cannot be NULL because we checked 'IsValidRegionCode()' above.
1138 const PhoneMetadata* metadata_calling_from =
1139 GetMetadataForRegion(calling_from);
1140 const string& international_prefix =
1141 metadata_calling_from->international_prefix();
1143 // For regions that have multiple international prefixes, the international
1144 // format of the number is returned, unless there is a preferred international
1146 const string international_prefix_for_formatting(
1147 reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1148 ? international_prefix
1149 : metadata_calling_from->preferred_international_prefix());
1152 GetRegionCodeForCountryCode(country_code, ®ion_code);
1153 // Metadata cannot be NULL because the country_code is valid.
1154 const PhoneMetadata* metadata_for_region =
1155 GetMetadataForRegionOrCallingCode(country_code, region_code);
1156 FormatNsn(national_significant_number, *metadata_for_region, INTERNATIONAL,
1158 MaybeAppendFormattedExtension(number, *metadata_for_region, INTERNATIONAL,
1160 if (!international_prefix_for_formatting.empty()) {
1161 formatted_number->insert(
1162 0, StrCat(international_prefix_for_formatting, " ", country_code, " "));
1164 PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1169 void PhoneNumberUtil::FormatInOriginalFormat(const PhoneNumber& number,
1170 const string& region_calling_from,
1171 string* formatted_number) const {
1172 DCHECK(formatted_number);
1174 if (number.has_raw_input() &&
1175 (HasUnexpectedItalianLeadingZero(number) ||
1176 !HasFormattingPatternForNumber(number))) {
1177 // We check if we have the formatting pattern because without that, we might
1178 // format the number as a group without national prefix.
1179 formatted_number->assign(number.raw_input());
1182 if (!number.has_country_code_source()) {
1183 Format(number, NATIONAL, formatted_number);
1186 switch (number.country_code_source()) {
1187 case PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN:
1188 Format(number, INTERNATIONAL, formatted_number);
1190 case PhoneNumber::FROM_NUMBER_WITH_IDD:
1191 FormatOutOfCountryCallingNumber(number, region_calling_from,
1194 case PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN:
1195 Format(number, INTERNATIONAL, formatted_number);
1196 formatted_number->erase(formatted_number->begin());
1198 case PhoneNumber::FROM_DEFAULT_COUNTRY:
1199 // Fall-through to default case.
1202 GetRegionCodeForCountryCode(number.country_code(), ®ion_code);
1203 // We strip non-digits from the NDD here, and from the raw input later, so
1204 // that we can compare them easily.
1205 string national_prefix;
1206 GetNddPrefixForRegion(region_code, true /* strip non-digits */,
1208 if (national_prefix.empty()) {
1209 // If the region doesn't have a national prefix at all, we can safely
1210 // return the national format without worrying about a national prefix
1212 Format(number, NATIONAL, formatted_number);
1215 // Otherwise, we check if the original number was entered with a national
1217 if (RawInputContainsNationalPrefix(number.raw_input(), national_prefix,
1219 // If so, we can safely return the national format.
1220 Format(number, NATIONAL, formatted_number);
1223 // Metadata cannot be NULL here because GetNddPrefixForRegion() (above)
1224 // leaves the prefix empty if there is no metadata for the region.
1225 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1226 string national_number;
1227 GetNationalSignificantNumber(number, &national_number);
1228 // This shouldn't be NULL, because we have checked that above with
1229 // HasFormattingPatternForNumber.
1230 const NumberFormat* format_rule =
1231 ChooseFormattingPatternForNumber(metadata->number_format(),
1233 // The format rule could still be NULL here if the national number was 0
1234 // and there was no raw input (this should not be possible for numbers
1235 // generated by the phonenumber library as they would also not have a
1236 // country calling code and we would have exited earlier).
1238 Format(number, NATIONAL, formatted_number);
1241 // When the format we apply to this number doesn't contain national
1242 // prefix, we can just return the national format.
1243 // TODO: Refactor the code below with the code in
1244 // IsNationalPrefixPresentIfRequired.
1245 string candidate_national_prefix_rule(
1246 format_rule->national_prefix_formatting_rule());
1247 // We assume that the first-group symbol will never be _before_ the
1249 if (!candidate_national_prefix_rule.empty()) {
1250 candidate_national_prefix_rule.erase(
1251 candidate_national_prefix_rule.find("$1"));
1252 NormalizeDigitsOnly(&candidate_national_prefix_rule);
1254 if (candidate_national_prefix_rule.empty()) {
1255 // National prefix not used when formatting this number.
1256 Format(number, NATIONAL, formatted_number);
1259 // Otherwise, we need to remove the national prefix from our output.
1260 RepeatedPtrField<NumberFormat> number_formats;
1261 NumberFormat* number_format = number_formats.Add();
1262 number_format->MergeFrom(*format_rule);
1263 number_format->clear_national_prefix_formatting_rule();
1264 FormatByPattern(number, NATIONAL, number_formats, formatted_number);
1267 // If no digit is inserted/removed/modified as a result of our formatting, we
1268 // return the formatted phone number; otherwise we return the raw input the
1270 if (!formatted_number->empty() && !number.raw_input().empty()) {
1271 string normalized_formatted_number(*formatted_number);
1272 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1273 true /* remove non matches */,
1274 &normalized_formatted_number);
1275 string normalized_raw_input(number.raw_input());
1276 NormalizeHelper(reg_exps_->diallable_char_mappings_,
1277 true /* remove non matches */, &normalized_raw_input);
1278 if (normalized_formatted_number != normalized_raw_input) {
1279 formatted_number->assign(number.raw_input());
1284 // Check if raw_input, which is assumed to be in the national format, has a
1285 // national prefix. The national prefix is assumed to be in digits-only form.
1286 bool PhoneNumberUtil::RawInputContainsNationalPrefix(
1287 const string& raw_input,
1288 const string& national_prefix,
1289 const string& region_code) const {
1290 string normalized_national_number(raw_input);
1291 NormalizeDigitsOnly(&normalized_national_number);
1292 if (HasPrefixString(normalized_national_number, national_prefix)) {
1293 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain
1294 // the national prefix when written without it (e.g. 0777123) if we just
1295 // do prefix matching. To tackle that, we check the validity of the
1296 // number if the assumed national prefix is removed (777123 won't be
1298 PhoneNumber number_without_national_prefix;
1299 if (Parse(normalized_national_number.substr(national_prefix.length()),
1300 region_code, &number_without_national_prefix)
1301 == NO_PARSING_ERROR) {
1302 return IsValidNumber(number_without_national_prefix);
1308 bool PhoneNumberUtil::HasUnexpectedItalianLeadingZero(
1309 const PhoneNumber& number) const {
1310 return number.has_italian_leading_zero() &&
1311 !IsLeadingZeroPossible(number.country_code());
1314 bool PhoneNumberUtil::HasFormattingPatternForNumber(
1315 const PhoneNumber& number) const {
1316 int country_calling_code = number.country_code();
1318 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
1319 const PhoneMetadata* metadata =
1320 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
1324 string national_number;
1325 GetNationalSignificantNumber(number, &national_number);
1326 const NumberFormat* format_rule =
1327 ChooseFormattingPatternForNumber(metadata->number_format(),
1332 void PhoneNumberUtil::FormatOutOfCountryKeepingAlphaChars(
1333 const PhoneNumber& number,
1334 const string& calling_from,
1335 string* formatted_number) const {
1336 // If there is no raw input, then we can't keep alpha characters because there
1337 // aren't any. In this case, we return FormatOutOfCountryCallingNumber.
1338 if (number.raw_input().empty()) {
1339 FormatOutOfCountryCallingNumber(number, calling_from, formatted_number);
1342 int country_code = number.country_code();
1343 if (!HasValidCountryCallingCode(country_code)) {
1344 formatted_number->assign(number.raw_input());
1347 // Strip any prefix such as country calling code, IDD, that was present. We do
1348 // this by comparing the number in raw_input with the parsed number.
1349 string raw_input_copy(number.raw_input());
1350 // Normalize punctuation. We retain number grouping symbols such as " " only.
1351 NormalizeHelper(reg_exps_->all_plus_number_grouping_symbols_, true,
1353 // Now we trim everything before the first three digits in the parsed number.
1354 // We choose three because all valid alpha numbers have 3 digits at the start
1355 // - if it does not, then we don't trim anything at all. Similarly, if the
1356 // national number was less than three digits, we don't trim anything at all.
1357 string national_number;
1358 GetNationalSignificantNumber(number, &national_number);
1359 if (national_number.length() > 3) {
1360 size_t first_national_number_digit =
1361 raw_input_copy.find(national_number.substr(0, 3));
1362 if (first_national_number_digit != string::npos) {
1363 raw_input_copy = raw_input_copy.substr(first_national_number_digit);
1366 const PhoneMetadata* metadata = GetMetadataForRegion(calling_from);
1367 if (country_code == kNanpaCountryCode) {
1368 if (IsNANPACountry(calling_from)) {
1369 StrAppend(formatted_number, country_code, " ", raw_input_copy);
1372 } else if (metadata &&
1373 country_code == GetCountryCodeForValidRegion(calling_from)) {
1374 const NumberFormat* formatting_pattern =
1375 ChooseFormattingPatternForNumber(metadata->number_format(),
1377 if (!formatting_pattern) {
1378 // If no pattern above is matched, we format the original input.
1379 formatted_number->assign(raw_input_copy);
1382 NumberFormat new_format;
1383 new_format.MergeFrom(*formatting_pattern);
1384 // The first group is the first group of digits that the user wrote
1386 new_format.set_pattern("(\\d+)(.*)");
1387 // Here we just concatenate them back together after the national prefix
1389 new_format.set_format("$1$2");
1390 // Now we format using this pattern instead of the default pattern, but
1391 // with the national prefix prefixed if necessary.
1392 // This will not work in the cases where the pattern (and not the
1393 // leading digits) decide whether a national prefix needs to be used, since
1394 // we have overridden the pattern to match anything, but that is not the
1395 // case in the metadata to date.
1396 FormatNsnUsingPattern(raw_input_copy, new_format, NATIONAL,
1401 string international_prefix_for_formatting;
1402 // If an unsupported region-calling-from is entered, or a country with
1403 // multiple international prefixes, the international format of the number is
1404 // returned, unless there is a preferred international prefix.
1406 const string& international_prefix = metadata->international_prefix();
1407 international_prefix_for_formatting =
1408 reg_exps_->unique_international_prefix_->FullMatch(international_prefix)
1409 ? international_prefix
1410 : metadata->preferred_international_prefix();
1412 if (!international_prefix_for_formatting.empty()) {
1413 StrAppend(formatted_number, international_prefix_for_formatting, " ",
1414 country_code, " ", raw_input_copy);
1416 // Invalid region entered as country-calling-from (so no metadata was found
1417 // for it) or the region chosen has multiple international dialling
1419 LOG(WARNING) << "Trying to format number from invalid region "
1421 << ". International formatting applied.";
1422 formatted_number->assign(raw_input_copy);
1423 PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL,
1428 const NumberFormat* PhoneNumberUtil::ChooseFormattingPatternForNumber(
1429 const RepeatedPtrField<NumberFormat>& available_formats,
1430 const string& national_number) const {
1431 for (RepeatedPtrField<NumberFormat>::const_iterator
1432 it = available_formats.begin(); it != available_formats.end(); ++it) {
1433 int size = it->leading_digits_pattern_size();
1435 const scoped_ptr<RegExpInput> number_copy(
1436 reg_exps_->regexp_factory_->CreateInput(national_number));
1437 // We always use the last leading_digits_pattern, as it is the most
1439 if (!reg_exps_->regexp_cache_->GetRegExp(
1440 it->leading_digits_pattern(size - 1)).Consume(
1441 number_copy.get())) {
1445 const RegExp& pattern_to_match(
1446 reg_exps_->regexp_cache_->GetRegExp(it->pattern()));
1447 if (pattern_to_match.FullMatch(national_number)) {
1454 // Note that carrier_code is optional - if an empty string, no carrier code
1455 // replacement will take place.
1456 void PhoneNumberUtil::FormatNsnUsingPatternWithCarrier(
1457 const string& national_number,
1458 const NumberFormat& formatting_pattern,
1459 PhoneNumberUtil::PhoneNumberFormat number_format,
1460 const string& carrier_code,
1461 string* formatted_number) const {
1462 DCHECK(formatted_number);
1463 string number_format_rule(formatting_pattern.format());
1464 if (number_format == PhoneNumberUtil::NATIONAL &&
1465 carrier_code.length() > 0 &&
1466 formatting_pattern.domestic_carrier_code_formatting_rule().length() > 0) {
1467 // Replace the $CC in the formatting rule with the desired carrier code.
1468 string carrier_code_formatting_rule =
1469 formatting_pattern.domestic_carrier_code_formatting_rule();
1470 reg_exps_->carrier_code_pattern_->Replace(&carrier_code_formatting_rule,
1472 reg_exps_->first_group_capturing_pattern_->
1473 Replace(&number_format_rule, carrier_code_formatting_rule);
1475 // Use the national prefix formatting rule instead.
1476 string national_prefix_formatting_rule =
1477 formatting_pattern.national_prefix_formatting_rule();
1478 if (number_format == PhoneNumberUtil::NATIONAL &&
1479 national_prefix_formatting_rule.length() > 0) {
1480 // Apply the national_prefix_formatting_rule as the formatting_pattern
1481 // contains only information on how the national significant number
1482 // should be formatted at this point.
1483 reg_exps_->first_group_capturing_pattern_->Replace(
1484 &number_format_rule, national_prefix_formatting_rule);
1487 formatted_number->assign(national_number);
1489 const RegExp& pattern_to_match(
1490 reg_exps_->regexp_cache_->GetRegExp(formatting_pattern.pattern()));
1491 pattern_to_match.GlobalReplace(formatted_number, number_format_rule);
1493 if (number_format == RFC3966) {
1494 // First consume any leading punctuation, if any was present.
1495 const scoped_ptr<RegExpInput> number(
1496 reg_exps_->regexp_factory_->CreateInput(*formatted_number));
1497 if (reg_exps_->separator_pattern_->Consume(number.get())) {
1498 formatted_number->assign(number->ToString());
1500 // Then replace all separators with a "-".
1501 reg_exps_->separator_pattern_->GlobalReplace(formatted_number, "-");
1505 // Simple wrapper of FormatNsnUsingPatternWithCarrier for the common case of
1507 void PhoneNumberUtil::FormatNsnUsingPattern(
1508 const string& national_number,
1509 const NumberFormat& formatting_pattern,
1510 PhoneNumberUtil::PhoneNumberFormat number_format,
1511 string* formatted_number) const {
1512 DCHECK(formatted_number);
1513 FormatNsnUsingPatternWithCarrier(national_number, formatting_pattern,
1514 number_format, "", formatted_number);
1517 void PhoneNumberUtil::FormatNsn(const string& number,
1518 const PhoneMetadata& metadata,
1519 PhoneNumberFormat number_format,
1520 string* formatted_number) const {
1521 DCHECK(formatted_number);
1522 FormatNsnWithCarrier(number, metadata, number_format, "", formatted_number);
1525 // Note in some regions, the national number can be written in two completely
1526 // different ways depending on whether it forms part of the NATIONAL format or
1527 // INTERNATIONAL format. The number_format parameter here is used to specify
1528 // which format to use for those cases. If a carrier_code is specified, this
1529 // will be inserted into the formatted string to replace $CC.
1530 void PhoneNumberUtil::FormatNsnWithCarrier(const string& number,
1531 const PhoneMetadata& metadata,
1532 PhoneNumberFormat number_format,
1533 const string& carrier_code,
1534 string* formatted_number) const {
1535 DCHECK(formatted_number);
1536 // When the intl_number_formats exists, we use that to format national number
1537 // for the INTERNATIONAL format instead of using the number_formats.
1538 const RepeatedPtrField<NumberFormat> available_formats =
1539 (metadata.intl_number_format_size() == 0 || number_format == NATIONAL)
1540 ? metadata.number_format()
1541 : metadata.intl_number_format();
1542 const NumberFormat* formatting_pattern =
1543 ChooseFormattingPatternForNumber(available_formats, number);
1544 if (!formatting_pattern) {
1545 formatted_number->assign(number);
1547 FormatNsnUsingPatternWithCarrier(number, *formatting_pattern, number_format,
1548 carrier_code, formatted_number);
1552 // Appends the formatted extension of a phone number, if the phone number had an
1553 // extension specified.
1554 void PhoneNumberUtil::MaybeAppendFormattedExtension(
1555 const PhoneNumber& number,
1556 const PhoneMetadata& metadata,
1557 PhoneNumberFormat number_format,
1558 string* formatted_number) const {
1559 DCHECK(formatted_number);
1560 if (number.has_extension() && number.extension().length() > 0) {
1561 if (number_format == RFC3966) {
1562 StrAppend(formatted_number, kRfc3966ExtnPrefix, number.extension());
1564 if (metadata.has_preferred_extn_prefix()) {
1565 StrAppend(formatted_number, metadata.preferred_extn_prefix(),
1566 number.extension());
1568 StrAppend(formatted_number, kDefaultExtnPrefix, number.extension());
1574 bool PhoneNumberUtil::IsNANPACountry(const string& region_code) const {
1575 return nanpa_regions_->find(region_code) != nanpa_regions_->end();
1578 // Returns the region codes that matches the specific country calling code. In
1579 // the case of no region code being found, region_codes will be left empty.
1580 void PhoneNumberUtil::GetRegionCodesForCountryCallingCode(
1581 int country_calling_code,
1582 list<string>* region_codes) const {
1583 DCHECK(region_codes);
1584 // Create a IntRegionsPair with the country_code passed in, and use it to
1585 // locate the pair with the same country_code in the sorted vector.
1586 IntRegionsPair target_pair;
1587 target_pair.first = country_calling_code;
1588 typedef vector<IntRegionsPair>::const_iterator ConstIterator;
1589 pair<ConstIterator, ConstIterator> range = equal_range(
1590 country_calling_code_to_region_code_map_->begin(),
1591 country_calling_code_to_region_code_map_->end(),
1592 target_pair, OrderByFirst());
1593 if (range.first != range.second) {
1594 region_codes->insert(region_codes->begin(),
1595 range.first->second->begin(),
1596 range.first->second->end());
1600 // Returns the region code that matches the specific country calling code. In
1601 // the case of no region code being found, the unknown region code will be
1603 void PhoneNumberUtil::GetRegionCodeForCountryCode(
1604 int country_calling_code,
1605 string* region_code) const {
1606 DCHECK(region_code);
1607 list<string> region_codes;
1609 GetRegionCodesForCountryCallingCode(country_calling_code, ®ion_codes);
1610 *region_code = (region_codes.size() > 0) ?
1611 region_codes.front() : RegionCode::GetUnknown();
1614 void PhoneNumberUtil::GetRegionCodeForNumber(const PhoneNumber& number,
1615 string* region_code) const {
1616 DCHECK(region_code);
1617 int country_calling_code = number.country_code();
1618 list<string> region_codes;
1619 GetRegionCodesForCountryCallingCode(country_calling_code, ®ion_codes);
1620 if (region_codes.size() == 0) {
1621 string number_string;
1622 GetNationalSignificantNumber(number, &number_string);
1623 LOG(WARNING) << "Missing/invalid country calling code ("
1624 << country_calling_code
1625 << ") for number " << number_string;
1626 *region_code = RegionCode::GetUnknown();
1629 if (region_codes.size() == 1) {
1630 *region_code = region_codes.front();
1632 GetRegionCodeForNumberFromRegionList(number, region_codes, region_code);
1636 void PhoneNumberUtil::GetRegionCodeForNumberFromRegionList(
1637 const PhoneNumber& number, const list<string>& region_codes,
1638 string* region_code) const {
1639 DCHECK(region_code);
1640 string national_number;
1641 GetNationalSignificantNumber(number, &national_number);
1642 for (list<string>::const_iterator it = region_codes.begin();
1643 it != region_codes.end(); ++it) {
1644 // Metadata cannot be NULL because the region codes come from the country
1645 // calling code map.
1646 const PhoneMetadata* metadata = GetMetadataForRegion(*it);
1647 if (metadata->has_leading_digits()) {
1648 const scoped_ptr<RegExpInput> number(
1649 reg_exps_->regexp_factory_->CreateInput(national_number));
1650 if (reg_exps_->regexp_cache_->
1651 GetRegExp(metadata->leading_digits()).Consume(number.get())) {
1655 } else if (GetNumberTypeHelper(national_number, *metadata,
1656 reg_exps_->regexp_cache_.get()) != UNKNOWN) {
1661 *region_code = RegionCode::GetUnknown();
1664 int PhoneNumberUtil::GetCountryCodeForRegion(const string& region_code) const {
1665 if (!IsValidRegionCode(region_code)) {
1666 LOG(WARNING) << "Invalid or unknown region code (" << region_code
1670 return GetCountryCodeForValidRegion(region_code);
1673 int PhoneNumberUtil::GetCountryCodeForValidRegion(
1674 const string& region_code) const {
1675 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
1676 return metadata->country_code();
1679 // Gets a valid fixed-line number for the specified region_code. Returns false
1680 // if the region was unknown or 001 (representing non-geographical regions), or
1681 // if no number exists.
1682 bool PhoneNumberUtil::GetExampleNumber(const string& region_code,
1683 PhoneNumber* number) const {
1685 return GetExampleNumberForType(region_code, FIXED_LINE, number);
1688 // Gets a valid number for the specified region_code and type. Returns false if
1689 // the country was unknown or 001 (representing non-geographical regions), or if
1690 // no number exists.
1691 bool PhoneNumberUtil::GetExampleNumberForType(
1692 const string& region_code,
1693 PhoneNumberUtil::PhoneNumberType type,
1694 PhoneNumber* number) const {
1696 if (!IsValidRegionCode(region_code)) {
1697 LOG(WARNING) << "Invalid or unknown region code (" << region_code
1701 const PhoneMetadata* region_metadata = GetMetadataForRegion(region_code);
1702 const PhoneNumberDesc* desc = GetNumberDescByType(*region_metadata, type);
1703 if (desc && desc->has_example_number()) {
1704 ErrorType success = Parse(desc->example_number(), region_code, number);
1705 if (success == NO_PARSING_ERROR) {
1708 LOG(ERROR) << "Error parsing example number ("
1709 << static_cast<int>(success) << ")";
1715 bool PhoneNumberUtil::GetExampleNumberForNonGeoEntity(
1716 int country_calling_code, PhoneNumber* number) const {
1718 const PhoneMetadata* metadata =
1719 GetMetadataForNonGeographicalRegion(country_calling_code);
1721 const PhoneNumberDesc& desc = metadata->general_desc();
1722 if (desc.has_example_number()) {
1723 ErrorType success = Parse(StrCat(kPlusSign,
1724 SimpleItoa(country_calling_code),
1725 desc.example_number()),
1726 RegionCode::ZZ(), number);
1727 if (success == NO_PARSING_ERROR) {
1730 LOG(ERROR) << "Error parsing example number ("
1731 << static_cast<int>(success) << ")";
1735 LOG(WARNING) << "Invalid or unknown country calling code provided: "
1736 << country_calling_code;
1741 PhoneNumberUtil::ErrorType PhoneNumberUtil::Parse(const string& number_to_parse,
1742 const string& default_region,
1743 PhoneNumber* number) const {
1745 return ParseHelper(number_to_parse, default_region, false, true, number);
1748 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseAndKeepRawInput(
1749 const string& number_to_parse,
1750 const string& default_region,
1751 PhoneNumber* number) const {
1753 return ParseHelper(number_to_parse, default_region, true, true, number);
1756 // Checks to see that the region code used is valid, or if it is not valid, that
1757 // the number to parse starts with a + symbol so that we can attempt to infer
1758 // the country from the number. Returns false if it cannot use the region
1759 // provided and the region cannot be inferred.
1760 bool PhoneNumberUtil::CheckRegionForParsing(
1761 const string& number_to_parse,
1762 const string& default_region) const {
1763 if (!IsValidRegionCode(default_region) && !number_to_parse.empty()) {
1764 const scoped_ptr<RegExpInput> number(
1765 reg_exps_->regexp_factory_->CreateInput(number_to_parse));
1766 if (!reg_exps_->plus_chars_pattern_->Consume(number.get())) {
1773 // Converts number_to_parse to a form that we can parse and write it to
1774 // national_number if it is written in RFC3966; otherwise extract a possible
1775 // number out of it and write to national_number.
1776 void PhoneNumberUtil::BuildNationalNumberForParsing(
1777 const string& number_to_parse, string* national_number) const {
1778 size_t index_of_phone_context = number_to_parse.find(kRfc3966PhoneContext);
1779 if (index_of_phone_context != string::npos) {
1780 int phone_context_start =
1781 index_of_phone_context + strlen(kRfc3966PhoneContext);
1782 // If the phone context contains a phone number prefix, we need to capture
1783 // it, whereas domains will be ignored.
1784 if (number_to_parse.at(phone_context_start) == kPlusSign[0]) {
1785 // Additional parameters might follow the phone context. If so, we will
1786 // remove them here because the parameters after phone context are not
1787 // important for parsing the phone number.
1788 size_t phone_context_end = number_to_parse.find(';', phone_context_start);
1789 if (phone_context_end != string::npos) {
1791 national_number, number_to_parse.substr(
1792 phone_context_start, phone_context_end - phone_context_start));
1794 StrAppend(national_number, number_to_parse.substr(phone_context_start));
1798 // Now append everything between the "tel:" prefix and the phone-context.
1799 // This should include the national number, an optional extension or
1800 // isdn-subaddress component.
1801 int end_of_rfc_prefix =
1802 number_to_parse.find(kRfc3966Prefix) + strlen(kRfc3966Prefix);
1805 number_to_parse.substr(end_of_rfc_prefix,
1806 index_of_phone_context - end_of_rfc_prefix));
1808 // Extract a possible number from the string passed in (this strips leading
1809 // characters that could not be the start of a phone number.)
1810 ExtractPossibleNumber(number_to_parse, national_number);
1813 // Delete the isdn-subaddress and everything after it if it is present. Note
1814 // extension won't appear at the same time with isdn-subaddress according to
1815 // paragraph 5.3 of the RFC3966 spec.
1816 size_t index_of_isdn = national_number->find(kRfc3966IsdnSubaddress);
1817 if (index_of_isdn != string::npos) {
1818 national_number->erase(index_of_isdn);
1820 // If both phone context and isdn-subaddress are absent but other parameters
1821 // are present, the parameters are left in nationalNumber. This is because
1822 // we are concerned about deleting content from a potential number string
1823 // when there is no strong evidence that the number is actually written in
1827 PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseHelper(
1828 const string& number_to_parse,
1829 const string& default_region,
1830 bool keep_raw_input,
1832 PhoneNumber* phone_number) const {
1833 DCHECK(phone_number);
1835 string national_number;
1836 BuildNationalNumberForParsing(number_to_parse, &national_number);
1838 if (!IsViablePhoneNumber(national_number)) {
1839 VLOG(2) << "The string supplied did not seem to be a phone number.";
1840 return NOT_A_NUMBER;
1844 !CheckRegionForParsing(national_number, default_region)) {
1845 VLOG(1) << "Missing or invalid default country.";
1846 return INVALID_COUNTRY_CODE_ERROR;
1848 PhoneNumber temp_number;
1849 if (keep_raw_input) {
1850 temp_number.set_raw_input(number_to_parse);
1852 // Attempt to parse extension first, since it doesn't require country-specific
1853 // data and we want to have the non-normalised number here.
1855 MaybeStripExtension(&national_number, &extension);
1856 if (!extension.empty()) {
1857 temp_number.set_extension(extension);
1859 const PhoneMetadata* country_metadata = GetMetadataForRegion(default_region);
1860 // Check to see if the number is given in international format so we know
1861 // whether this number is from the default country or not.
1862 string normalized_national_number(national_number);
1863 ErrorType country_code_error =
1864 MaybeExtractCountryCode(country_metadata, keep_raw_input,
1865 &normalized_national_number, &temp_number);
1866 if (country_code_error != NO_PARSING_ERROR) {
1867 const scoped_ptr<RegExpInput> number_string_piece(
1868 reg_exps_->regexp_factory_->CreateInput(national_number));
1869 if ((country_code_error == INVALID_COUNTRY_CODE_ERROR) &&
1870 (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get()))) {
1871 normalized_national_number.assign(number_string_piece->ToString());
1872 // Strip the plus-char, and try again.
1873 MaybeExtractCountryCode(country_metadata,
1875 &normalized_national_number,
1877 if (temp_number.country_code() == 0) {
1878 return INVALID_COUNTRY_CODE_ERROR;
1881 return country_code_error;
1884 int country_code = temp_number.country_code();
1885 if (country_code != 0) {
1886 string phone_number_region;
1887 GetRegionCodeForCountryCode(country_code, &phone_number_region);
1888 if (phone_number_region != default_region) {
1890 GetMetadataForRegionOrCallingCode(country_code, phone_number_region);
1892 } else if (country_metadata) {
1893 // If no extracted country calling code, use the region supplied instead.
1894 // Note that the national number was already normalized by
1895 // MaybeExtractCountryCode.
1896 country_code = country_metadata->country_code();
1898 if (normalized_national_number.length() < kMinLengthForNsn) {
1899 VLOG(2) << "The string supplied is too short to be a phone number.";
1900 return TOO_SHORT_NSN;
1902 if (country_metadata) {
1903 string* carrier_code = keep_raw_input ?
1904 temp_number.mutable_preferred_domestic_carrier_code() : NULL;
1905 MaybeStripNationalPrefixAndCarrierCode(*country_metadata,
1906 &normalized_national_number,
1909 size_t normalized_national_number_length =
1910 normalized_national_number.length();
1911 if (normalized_national_number_length < kMinLengthForNsn) {
1912 VLOG(2) << "The string supplied is too short to be a phone number.";
1913 return TOO_SHORT_NSN;
1915 if (normalized_national_number_length > kMaxLengthForNsn) {
1916 VLOG(2) << "The string supplied is too long to be a phone number.";
1917 return TOO_LONG_NSN;
1919 temp_number.set_country_code(country_code);
1920 if (normalized_national_number[0] == '0') {
1921 temp_number.set_italian_leading_zero(true);
1923 uint64 number_as_int;
1924 safe_strtou64(normalized_national_number, &number_as_int);
1925 temp_number.set_national_number(number_as_int);
1926 phone_number->MergeFrom(temp_number);
1927 return NO_PARSING_ERROR;
1930 // Attempts to extract a possible number from the string passed in. This
1931 // currently strips all leading characters that could not be used to start a
1932 // phone number. Characters that can be used to start a phone number are
1933 // defined in the valid_start_char_pattern. If none of these characters are
1934 // found in the number passed in, an empty string is returned. This function
1935 // also attempts to strip off any alternative extensions or endings if two or
1936 // more are present, such as in the case of: (530) 583-6985 x302/x2303. The
1937 // second extension here makes this actually two phone numbers, (530) 583-6985
1938 // x302 and (530) 583-6985 x2303. We remove the second extension so that the
1939 // first number is parsed correctly.
1940 void PhoneNumberUtil::ExtractPossibleNumber(const string& number,
1941 string* extracted_number) const {
1942 DCHECK(extracted_number);
1944 UnicodeText number_as_unicode;
1945 number_as_unicode.PointToUTF8(number.data(), number.size());
1946 char current_char[5];
1948 UnicodeText::const_iterator it;
1949 for (it = number_as_unicode.begin(); it != number_as_unicode.end(); ++it) {
1950 len = it.get_utf8(current_char);
1951 current_char[len] = '\0';
1952 if (reg_exps_->valid_start_char_pattern_->FullMatch(current_char)) {
1957 if (it == number_as_unicode.end()) {
1958 // No valid start character was found. extracted_number should be set to
1960 extracted_number->assign("");
1964 extracted_number->assign(
1965 UnicodeText::UTF8Substring(it, number_as_unicode.end()));
1966 TrimUnwantedEndChars(extracted_number);
1967 if (extracted_number->length() == 0) {
1971 VLOG(3) << "After stripping starting and trailing characters, left with: "
1972 << *extracted_number;
1974 // Now remove any extra numbers at the end.
1975 reg_exps_->capture_up_to_second_number_start_pattern_->
1976 PartialMatch(*extracted_number, extracted_number);
1979 bool PhoneNumberUtil::IsPossibleNumber(const PhoneNumber& number) const {
1980 return IsPossibleNumberWithReason(number) == IS_POSSIBLE;
1983 bool PhoneNumberUtil::IsPossibleNumberForString(
1984 const string& number,
1985 const string& region_dialing_from) const {
1986 PhoneNumber number_proto;
1987 if (Parse(number, region_dialing_from, &number_proto) == NO_PARSING_ERROR) {
1988 return IsPossibleNumber(number_proto);
1994 PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberWithReason(
1995 const PhoneNumber& number) const {
1996 string national_number;
1997 GetNationalSignificantNumber(number, &national_number);
1998 int country_code = number.country_code();
1999 // Note: For Russian Fed and NANPA numbers, we just use the rules from the
2000 // default region (US or Russia) since the GetRegionCodeForNumber will not
2001 // work if the number is possible but not valid. This would need to be
2002 // revisited if the possible number pattern ever differed between various
2003 // regions within those plans.
2004 if (!HasValidCountryCallingCode(country_code)) {
2005 return INVALID_COUNTRY_CODE;
2008 GetRegionCodeForCountryCode(country_code, ®ion_code);
2009 // Metadata cannot be NULL because the country calling code is valid.
2010 const PhoneMetadata* metadata =
2011 GetMetadataForRegionOrCallingCode(country_code, region_code);
2012 const PhoneNumberDesc& general_num_desc = metadata->general_desc();
2013 // Handling case of numbers with no metadata.
2014 if (!general_num_desc.has_national_number_pattern()) {
2015 size_t number_length = national_number.length();
2016 if (number_length < kMinLengthForNsn) {
2018 } else if (number_length > kMaxLengthForNsn) {
2024 const RegExp& possible_number_pattern = reg_exps_->regexp_cache_->GetRegExp(
2025 StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2026 return TestNumberLengthAgainstPattern(possible_number_pattern,
2030 bool PhoneNumberUtil::TruncateTooLongNumber(PhoneNumber* number) const {
2031 if (IsValidNumber(*number)) {
2034 PhoneNumber number_copy(*number);
2035 uint64 national_number = number->national_number();
2037 national_number /= 10;
2038 number_copy.set_national_number(national_number);
2039 if (IsPossibleNumberWithReason(number_copy) == TOO_SHORT ||
2040 national_number == 0) {
2043 } while (!IsValidNumber(number_copy));
2044 number->set_national_number(national_number);
2048 PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberType(
2049 const PhoneNumber& number) const {
2051 GetRegionCodeForNumber(number, ®ion_code);
2052 const PhoneMetadata* metadata =
2053 GetMetadataForRegionOrCallingCode(number.country_code(), region_code);
2057 string national_significant_number;
2058 GetNationalSignificantNumber(number, &national_significant_number);
2059 return GetNumberTypeHelper(national_significant_number,
2061 reg_exps_->regexp_cache_.get());
2064 bool PhoneNumberUtil::IsValidNumber(const PhoneNumber& number) const {
2066 GetRegionCodeForNumber(number, ®ion_code);
2067 return IsValidNumberForRegion(number, region_code);
2070 bool PhoneNumberUtil::IsValidNumberForRegion(const PhoneNumber& number,
2071 const string& region_code) const {
2072 int country_code = number.country_code();
2073 const PhoneMetadata* metadata =
2074 GetMetadataForRegionOrCallingCode(country_code, region_code);
2076 ((kRegionCodeForNonGeoEntity != region_code) &&
2077 country_code != GetCountryCodeForValidRegion(region_code))) {
2078 // Either the region code was invalid, or the country calling code for this
2079 // number does not match that of the region code.
2082 const PhoneNumberDesc& general_desc = metadata->general_desc();
2083 string national_number;
2084 GetNationalSignificantNumber(number, &national_number);
2086 // For regions where we don't have metadata for PhoneNumberDesc, we treat
2087 // any number passed in as a valid number if its national significant number
2088 // is between the minimum and maximum lengths defined by ITU for a national
2089 // significant number.
2090 if (!general_desc.has_national_number_pattern()) {
2091 VLOG(3) << "Validating number with incomplete metadata.";
2092 size_t number_length = national_number.length();
2093 return number_length > kMinLengthForNsn &&
2094 number_length <= kMaxLengthForNsn;
2096 return GetNumberTypeHelper(national_number, *metadata,
2097 reg_exps_->regexp_cache_.get()) != UNKNOWN;
2100 bool PhoneNumberUtil::IsNumberGeographical(
2101 const PhoneNumber& phone_number) const {
2102 PhoneNumberType number_type = GetNumberType(phone_number);
2103 // TODO: Include mobile phone numbers from countries like
2104 // Indonesia, which has some mobile numbers that are geographical.
2105 return number_type == PhoneNumberUtil::FIXED_LINE ||
2106 number_type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE;
2109 bool PhoneNumberUtil::IsLeadingZeroPossible(int country_calling_code) const {
2111 GetRegionCodeForCountryCode(country_calling_code, ®ion_code);
2112 const PhoneMetadata* main_metadata_for_calling_code =
2113 GetMetadataForRegionOrCallingCode(country_calling_code, region_code);
2114 if (!main_metadata_for_calling_code) return false;
2115 return main_metadata_for_calling_code->leading_zero_possible();
2118 void PhoneNumberUtil::GetNationalSignificantNumber(
2119 const PhoneNumber& number,
2120 string* national_number) const {
2121 DCHECK(national_number);
2122 // If a leading zero has been set, we prefix this now. Note this is not a
2124 StrAppend(national_number, number.italian_leading_zero() ? "0" : "");
2125 StrAppend(national_number, number.national_number());
2128 int PhoneNumberUtil::GetLengthOfGeographicalAreaCode(
2129 const PhoneNumber& number) const {
2131 GetRegionCodeForNumber(number, ®ion_code);
2132 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2136 // If a country doesn't use a national prefix, and this number doesn't have an
2137 // Italian leading zero, we assume it is a closed dialling plan with no area
2139 if (!metadata->has_national_prefix() && !number.italian_leading_zero()) {
2143 if (!IsNumberGeographical(number)) {
2147 return GetLengthOfNationalDestinationCode(number);
2150 int PhoneNumberUtil::GetLengthOfNationalDestinationCode(
2151 const PhoneNumber& number) const {
2152 PhoneNumber copied_proto(number);
2153 if (number.has_extension()) {
2154 // Clear the extension so it's not included when formatting.
2155 copied_proto.clear_extension();
2158 string formatted_number;
2159 Format(copied_proto, INTERNATIONAL, &formatted_number);
2160 const scoped_ptr<RegExpInput> i18n_number(
2161 reg_exps_->regexp_factory_->CreateInput(formatted_number));
2165 for (int i = 0; i < 3; ++i) {
2166 if (!reg_exps_->capturing_ascii_digits_pattern_->FindAndConsume(
2167 i18n_number.get(), &digit_group)) {
2168 // We should find at least three groups.
2173 } else if (i == 2) {
2174 third_group = digit_group;
2178 GetRegionCodeForCountryCode(number.country_code(), ®ion_code);
2179 if (region_code == "AR" &&
2180 GetNumberType(number) == MOBILE) {
2181 // Argentinian mobile numbers, when formatted in the international format,
2182 // are in the form of +54 9 NDC XXXX.... As a result, we take the length of
2183 // the third group (NDC) and add 1 for the digit 9, which also forms part of
2184 // the national significant number.
2185 return third_group.size() + 1;
2190 void PhoneNumberUtil::NormalizeDigitsOnly(string* number) const {
2192 const RegExp& non_digits_pattern = reg_exps_->regexp_cache_->GetRegExp(
2193 StrCat("[^", kDigits, "]"));
2194 // Delete everything that isn't valid digits.
2195 non_digits_pattern.GlobalReplace(number, "");
2196 // Normalize all decimal digits to ASCII digits.
2197 number->assign(NormalizeUTF8::NormalizeDecimalDigits(*number));
2200 bool PhoneNumberUtil::IsAlphaNumber(const string& number) const {
2201 if (!IsViablePhoneNumber(number)) {
2202 // Number is too short, or doesn't match the basic phone number pattern.
2205 // Copy the number, since we are going to try and strip the extension from it.
2206 string number_copy(number);
2208 MaybeStripExtension(&number_copy, &extension);
2209 return reg_exps_->valid_alpha_phone_pattern_->FullMatch(number_copy);
2212 void PhoneNumberUtil::ConvertAlphaCharactersInNumber(string* number) const {
2214 NormalizeHelper(reg_exps_->alpha_phone_mappings_, false, number);
2217 // Normalizes a string of characters representing a phone number. This performs
2218 // the following conversions:
2219 // - Punctuation is stripped.
2220 // For ALPHA/VANITY numbers:
2221 // - Letters are converted to their numeric representation on a telephone
2222 // keypad. The keypad used here is the one defined in ITU Recommendation
2223 // E.161. This is only done if there are 3 or more letters in the number, to
2224 // lessen the risk that such letters are typos.
2225 // For other numbers:
2226 // - Wide-ascii digits are converted to normal ASCII (European) digits.
2227 // - Arabic-Indic numerals are converted to European numerals.
2228 // - Spurious alpha characters are stripped.
2229 void PhoneNumberUtil::Normalize(string* number) const {
2231 if (reg_exps_->valid_alpha_phone_pattern_->PartialMatch(*number)) {
2232 NormalizeHelper(reg_exps_->alpha_phone_mappings_, true, number);
2234 NormalizeDigitsOnly(number);
2237 // Checks to see if the string of characters could possibly be a phone number at
2238 // all. At the moment, checks to see that the string begins with at least 3
2239 // digits, ignoring any punctuation commonly found in phone numbers. This
2240 // method does not require the number to be normalized in advance - but does
2241 // assume that leading non-number symbols have been removed, such as by the
2242 // method ExtractPossibleNumber.
2243 bool PhoneNumberUtil::IsViablePhoneNumber(const string& number) const {
2244 if (number.length() < kMinLengthForNsn) {
2245 VLOG(2) << "Number too short to be viable:" << number;
2248 return reg_exps_->valid_phone_number_pattern_->FullMatch(number);
2251 // Strips the IDD from the start of the number if present. Helper function used
2252 // by MaybeStripInternationalPrefixAndNormalize.
2253 bool PhoneNumberUtil::ParsePrefixAsIdd(const RegExp& idd_pattern,
2254 string* number) const {
2256 const scoped_ptr<RegExpInput> number_copy(
2257 reg_exps_->regexp_factory_->CreateInput(*number));
2258 // First attempt to strip the idd_pattern at the start, if present. We make a
2259 // copy so that we can revert to the original string if necessary.
2260 if (idd_pattern.Consume(number_copy.get())) {
2261 // Only strip this if the first digit after the match is not a 0, since
2262 // country calling codes cannot begin with 0.
2263 string extracted_digit;
2264 if (reg_exps_->capturing_digit_pattern_->PartialMatch(
2265 number_copy->ToString(), &extracted_digit)) {
2266 NormalizeDigitsOnly(&extracted_digit);
2267 if (extracted_digit == "0") {
2271 number->assign(number_copy->ToString());
2277 // Strips any international prefix (such as +, 00, 011) present in the number
2278 // provided, normalizes the resulting number, and indicates if an international
2279 // prefix was present.
2281 // possible_idd_prefix represents the international direct dialing prefix from
2282 // the region we think this number may be dialed in.
2283 // Returns true if an international dialing prefix could be removed from the
2284 // number, otherwise false if the number did not seem to be in international
2286 PhoneNumber::CountryCodeSource
2287 PhoneNumberUtil::MaybeStripInternationalPrefixAndNormalize(
2288 const string& possible_idd_prefix,
2289 string* number) const {
2291 if (number->empty()) {
2292 return PhoneNumber::FROM_DEFAULT_COUNTRY;
2294 const scoped_ptr<RegExpInput> number_string_piece(
2295 reg_exps_->regexp_factory_->CreateInput(*number));
2296 if (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get())) {
2297 number->assign(number_string_piece->ToString());
2298 // Can now normalize the rest of the number since we've consumed the "+"
2299 // sign at the start.
2301 return PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN;
2303 // Attempt to parse the first digits as an international prefix.
2304 const RegExp& idd_pattern =
2305 reg_exps_->regexp_cache_->GetRegExp(possible_idd_prefix);
2307 return ParsePrefixAsIdd(idd_pattern, number)
2308 ? PhoneNumber::FROM_NUMBER_WITH_IDD
2309 : PhoneNumber::FROM_DEFAULT_COUNTRY;
2312 // Strips any national prefix (such as 0, 1) present in the number provided.
2313 // The number passed in should be the normalized telephone number that we wish
2314 // to strip any national dialing prefix from. The metadata should be for the
2315 // region that we think this number is from. Returns true if a national prefix
2316 // and/or carrier code was stripped.
2317 bool PhoneNumberUtil::MaybeStripNationalPrefixAndCarrierCode(
2318 const PhoneMetadata& metadata,
2320 string* carrier_code) const {
2322 string carrier_code_temp;
2323 const string& possible_national_prefix =
2324 metadata.national_prefix_for_parsing();
2325 if (number->empty() || possible_national_prefix.empty()) {
2326 // Early return for numbers of zero length or with no national prefix
2330 // We use two copies here since Consume modifies the phone number, and if the
2331 // first if-clause fails the number will already be changed.
2332 const scoped_ptr<RegExpInput> number_copy(
2333 reg_exps_->regexp_factory_->CreateInput(*number));
2334 const scoped_ptr<RegExpInput> number_copy_without_transform(
2335 reg_exps_->regexp_factory_->CreateInput(*number));
2336 string number_string_copy(*number);
2337 string captured_part_of_prefix;
2338 const RegExp& national_number_rule = reg_exps_->regexp_cache_->GetRegExp(
2339 metadata.general_desc().national_number_pattern());
2340 // Check if the original number is viable.
2341 bool is_viable_original_number = national_number_rule.FullMatch(*number);
2342 // Attempt to parse the first digits as a national prefix. We make a
2343 // copy so that we can revert to the original string if necessary.
2344 const string& transform_rule = metadata.national_prefix_transform_rule();
2345 const RegExp& possible_national_prefix_pattern =
2346 reg_exps_->regexp_cache_->GetRegExp(possible_national_prefix);
2347 if (!transform_rule.empty() &&
2348 (possible_national_prefix_pattern.Consume(
2349 number_copy.get(), &carrier_code_temp, &captured_part_of_prefix) ||
2350 possible_national_prefix_pattern.Consume(
2351 number_copy.get(), &captured_part_of_prefix)) &&
2352 !captured_part_of_prefix.empty()) {
2353 // If this succeeded, then we must have had a transform rule and there must
2354 // have been some part of the prefix that we captured.
2355 // We make the transformation and check that the resultant number is still
2356 // viable. If so, replace the number and return.
2357 possible_national_prefix_pattern.Replace(&number_string_copy,
2359 if (is_viable_original_number &&
2360 !national_number_rule.FullMatch(number_string_copy)) {
2363 number->assign(number_string_copy);
2365 carrier_code->assign(carrier_code_temp);
2367 } else if (possible_national_prefix_pattern.Consume(
2368 number_copy_without_transform.get(), &carrier_code_temp) ||
2369 possible_national_prefix_pattern.Consume(
2370 number_copy_without_transform.get())) {
2371 VLOG(4) << "Parsed the first digits as a national prefix.";
2372 // If captured_part_of_prefix is empty, this implies nothing was captured by
2373 // the capturing groups in possible_national_prefix; therefore, no
2374 // transformation is necessary, and we just remove the national prefix.
2375 const string number_copy_as_string =
2376 number_copy_without_transform->ToString();
2377 if (is_viable_original_number &&
2378 !national_number_rule.FullMatch(number_copy_as_string)) {
2381 number->assign(number_copy_as_string);
2383 carrier_code->assign(carrier_code_temp);
2387 VLOG(4) << "The first digits did not match the national prefix.";
2392 // Strips any extension (as in, the part of the number dialled after the call is
2393 // connected, usually indicated with extn, ext, x or similar) from the end of
2394 // the number, and returns it. The number passed in should be non-normalized.
2395 bool PhoneNumberUtil::MaybeStripExtension(string* number, string* extension)
2399 // There are three extension capturing groups in the regular expression.
2400 string possible_extension_one;
2401 string possible_extension_two;
2402 string possible_extension_three;
2403 string number_copy(*number);
2404 const scoped_ptr<RegExpInput> number_copy_as_regexp_input(
2405 reg_exps_->regexp_factory_->CreateInput(number_copy));
2406 if (reg_exps_->extn_pattern_->Consume(number_copy_as_regexp_input.get(),
2408 &possible_extension_one,
2409 &possible_extension_two,
2410 &possible_extension_three)) {
2411 // Replace the extensions in the original string here.
2412 reg_exps_->extn_pattern_->Replace(&number_copy, "");
2413 VLOG(4) << "Found an extension. Possible extension one: "
2414 << possible_extension_one
2415 << ". Possible extension two: " << possible_extension_two
2416 << ". Possible extension three: " << possible_extension_three
2417 << ". Remaining number: " << number_copy;
2418 // If we find a potential extension, and the number preceding this is a
2419 // viable number, we assume it is an extension.
2420 if ((!possible_extension_one.empty() || !possible_extension_two.empty() ||
2421 !possible_extension_three.empty()) &&
2422 IsViablePhoneNumber(number_copy)) {
2423 number->assign(number_copy);
2424 if (!possible_extension_one.empty()) {
2425 extension->assign(possible_extension_one);
2426 } else if (!possible_extension_two.empty()) {
2427 extension->assign(possible_extension_two);
2428 } else if (!possible_extension_three.empty()) {
2429 extension->assign(possible_extension_three);
2437 // Extracts country calling code from national_number, and returns it. It
2438 // assumes that the leading plus sign or IDD has already been removed. Returns 0
2439 // if national_number doesn't start with a valid country calling code, and
2440 // leaves national_number unmodified. Assumes the national_number is at least 3
2442 int PhoneNumberUtil::ExtractCountryCode(string* national_number) const {
2443 int potential_country_code;
2444 if (national_number->empty() || (national_number->at(0) == '0')) {
2445 // Country codes do not begin with a '0'.
2448 for (size_t i = 1; i <= kMaxLengthCountryCode; ++i) {
2449 safe_strto32(national_number->substr(0, i), &potential_country_code);
2451 GetRegionCodeForCountryCode(potential_country_code, ®ion_code);
2452 if (region_code != RegionCode::GetUnknown()) {
2453 national_number->erase(0, i);
2454 return potential_country_code;
2460 // Tries to extract a country calling code from a number. Country calling codes
2461 // are extracted in the following ways:
2462 // - by stripping the international dialing prefix of the region the person
2463 // is dialing from, if this is present in the number, and looking at the next
2465 // - by stripping the '+' sign if present and then looking at the next digits
2466 // - by comparing the start of the number and the country calling code of the
2467 // default region. If the number is not considered possible for the numbering
2468 // plan of the default region initially, but starts with the country calling
2469 // code of this region, validation will be reattempted after stripping this
2470 // country calling code. If this number is considered a possible number, then
2471 // the first digits will be considered the country calling code and removed as
2474 // Returns NO_PARSING_ERROR if a country calling code was successfully
2475 // extracted or none was present, or the appropriate error otherwise, such as
2476 // if a + was present but it was not followed by a valid country calling code.
2477 // If NO_PARSING_ERROR is returned, the national_number without the country
2478 // calling code is populated, and the country_code of the phone_number passed
2479 // in is set to the country calling code if found, otherwise to 0.
2480 PhoneNumberUtil::ErrorType PhoneNumberUtil::MaybeExtractCountryCode(
2481 const PhoneMetadata* default_region_metadata,
2482 bool keep_raw_input,
2483 string* national_number,
2484 PhoneNumber* phone_number) const {
2485 DCHECK(national_number);
2486 DCHECK(phone_number);
2487 // Set the default prefix to be something that will never match if there is no
2489 string possible_country_idd_prefix = default_region_metadata
2490 ? default_region_metadata->international_prefix()
2492 PhoneNumber::CountryCodeSource country_code_source =
2493 MaybeStripInternationalPrefixAndNormalize(possible_country_idd_prefix,
2495 if (keep_raw_input) {
2496 phone_number->set_country_code_source(country_code_source);
2498 if (country_code_source != PhoneNumber::FROM_DEFAULT_COUNTRY) {
2499 if (national_number->length() <= kMinLengthForNsn) {
2500 VLOG(2) << "Phone number had an IDD, but after this was not "
2501 << "long enough to be a viable phone number.";
2502 return TOO_SHORT_AFTER_IDD;
2504 int potential_country_code = ExtractCountryCode(national_number);
2505 if (potential_country_code != 0) {
2506 phone_number->set_country_code(potential_country_code);
2507 return NO_PARSING_ERROR;
2509 // If this fails, they must be using a strange country calling code that we
2510 // don't recognize, or that doesn't exist.
2511 return INVALID_COUNTRY_CODE_ERROR;
2512 } else if (default_region_metadata) {
2513 // Check to see if the number starts with the country calling code for the
2514 // default region. If so, we remove the country calling code, and do some
2515 // checks on the validity of the number before and after.
2516 int default_country_code = default_region_metadata->country_code();
2517 string default_country_code_string(SimpleItoa(default_country_code));
2518 VLOG(4) << "Possible country calling code: " << default_country_code_string;
2519 string potential_national_number;
2520 if (TryStripPrefixString(*national_number,
2521 default_country_code_string,
2522 &potential_national_number)) {
2523 const PhoneNumberDesc& general_num_desc =
2524 default_region_metadata->general_desc();
2525 const RegExp& valid_number_pattern =
2526 reg_exps_->regexp_cache_->GetRegExp(
2527 general_num_desc.national_number_pattern());
2528 MaybeStripNationalPrefixAndCarrierCode(*default_region_metadata,
2529 &potential_national_number,
2531 VLOG(4) << "Number without country calling code prefix: "
2532 << potential_national_number;
2533 const RegExp& possible_number_pattern =
2534 reg_exps_->regexp_cache_->GetRegExp(
2535 StrCat("(", general_num_desc.possible_number_pattern(), ")"));
2536 // If the number was not valid before but is valid now, or if it was too
2537 // long before, we consider the number with the country code stripped to
2538 // be a better result and keep that instead.
2539 if ((!valid_number_pattern.FullMatch(*national_number) &&
2540 valid_number_pattern.FullMatch(potential_national_number)) ||
2541 TestNumberLengthAgainstPattern(possible_number_pattern,
2542 *national_number) == TOO_LONG) {
2543 national_number->assign(potential_national_number);
2544 if (keep_raw_input) {
2545 phone_number->set_country_code_source(
2546 PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN);
2548 phone_number->set_country_code(default_country_code);
2549 return NO_PARSING_ERROR;
2553 // No country calling code present. Set the country_code to 0.
2554 phone_number->set_country_code(0);
2555 return NO_PARSING_ERROR;
2558 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatch(
2559 const PhoneNumber& first_number_in,
2560 const PhoneNumber& second_number_in) const {
2561 // Make copies of the phone number so that the numbers passed in are not
2563 PhoneNumber first_number(first_number_in);
2564 PhoneNumber second_number(second_number_in);
2565 // First clear raw_input and country_code_source and
2566 // preferred_domestic_carrier_code fields and any empty-string extensions so
2567 // that we can use the proto-buffer equality method.
2568 first_number.clear_raw_input();
2569 first_number.clear_country_code_source();
2570 first_number.clear_preferred_domestic_carrier_code();
2571 second_number.clear_raw_input();
2572 second_number.clear_country_code_source();
2573 second_number.clear_preferred_domestic_carrier_code();
2574 if (first_number.extension().empty()) {
2575 first_number.clear_extension();
2577 if (second_number.extension().empty()) {
2578 second_number.clear_extension();
2580 // Early exit if both had extensions and these are different.
2581 if (first_number.has_extension() && second_number.has_extension() &&
2582 first_number.extension() != second_number.extension()) {
2585 int first_number_country_code = first_number.country_code();
2586 int second_number_country_code = second_number.country_code();
2587 // Both had country calling code specified.
2588 if (first_number_country_code != 0 && second_number_country_code != 0) {
2589 if (ExactlySameAs(first_number, second_number)) {
2591 } else if (first_number_country_code == second_number_country_code &&
2592 IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2593 // A SHORT_NSN_MATCH occurs if there is a difference because of the
2594 // presence or absence of an 'Italian leading zero', the presence or
2595 // absence of an extension, or one NSN being a shorter variant of the
2597 return SHORT_NSN_MATCH;
2599 // This is not a match.
2602 // Checks cases where one or both country calling codes were not specified. To
2603 // make equality checks easier, we first set the country_code fields to be
2605 first_number.set_country_code(second_number_country_code);
2606 // If all else was the same, then this is an NSN_MATCH.
2607 if (ExactlySameAs(first_number, second_number)) {
2610 if (IsNationalNumberSuffixOfTheOther(first_number, second_number)) {
2611 return SHORT_NSN_MATCH;
2616 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithTwoStrings(
2617 const string& first_number,
2618 const string& second_number) const {
2619 PhoneNumber first_number_as_proto;
2620 ErrorType error_type =
2621 Parse(first_number, RegionCode::GetUnknown(), &first_number_as_proto);
2622 if (error_type == NO_PARSING_ERROR) {
2623 return IsNumberMatchWithOneString(first_number_as_proto, second_number);
2625 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2626 PhoneNumber second_number_as_proto;
2627 ErrorType error_type = Parse(second_number, RegionCode::GetUnknown(),
2628 &second_number_as_proto);
2629 if (error_type == NO_PARSING_ERROR) {
2630 return IsNumberMatchWithOneString(second_number_as_proto, first_number);
2632 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2633 error_type = ParseHelper(first_number, RegionCode::GetUnknown(), false,
2634 false, &first_number_as_proto);
2635 if (error_type == NO_PARSING_ERROR) {
2636 error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2637 false, &second_number_as_proto);
2638 if (error_type == NO_PARSING_ERROR) {
2639 return IsNumberMatch(first_number_as_proto, second_number_as_proto);
2644 // One or more of the phone numbers we are trying to match is not a viable
2646 return INVALID_NUMBER;
2649 PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithOneString(
2650 const PhoneNumber& first_number,
2651 const string& second_number) const {
2652 // First see if the second number has an implicit country calling code, by
2653 // attempting to parse it.
2654 PhoneNumber second_number_as_proto;
2655 ErrorType error_type =
2656 Parse(second_number, RegionCode::GetUnknown(), &second_number_as_proto);
2657 if (error_type == NO_PARSING_ERROR) {
2658 return IsNumberMatch(first_number, second_number_as_proto);
2660 if (error_type == INVALID_COUNTRY_CODE_ERROR) {
2661 // The second number has no country calling code. EXACT_MATCH is no longer
2662 // possible. We parse it as if the region was the same as that for the
2663 // first number, and if EXACT_MATCH is returned, we replace this with
2665 string first_number_region;
2666 GetRegionCodeForCountryCode(first_number.country_code(),
2667 &first_number_region);
2668 if (first_number_region != RegionCode::GetUnknown()) {
2669 PhoneNumber second_number_with_first_number_region;
2670 Parse(second_number, first_number_region,
2671 &second_number_with_first_number_region);
2672 MatchType match = IsNumberMatch(first_number,
2673 second_number_with_first_number_region);
2674 if (match == EXACT_MATCH) {
2679 // If the first number didn't have a valid country calling code, then we
2680 // parse the second number without one as well.
2681 error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false,
2682 false, &second_number_as_proto);
2683 if (error_type == NO_PARSING_ERROR) {
2684 return IsNumberMatch(first_number, second_number_as_proto);
2688 // One or more of the phone numbers we are trying to match is not a viable
2690 return INVALID_NUMBER;
2693 AsYouTypeFormatter* PhoneNumberUtil::GetAsYouTypeFormatter(
2694 const string& region_code) const {
2695 return new AsYouTypeFormatter(region_code);
2698 bool PhoneNumberUtil::CanBeInternationallyDialled(
2699 const PhoneNumber& number) const {
2701 GetRegionCodeForNumber(number, ®ion_code);
2702 const PhoneMetadata* metadata = GetMetadataForRegion(region_code);
2704 // Note numbers belonging to non-geographical entities (e.g. +800 numbers)
2705 // are always internationally diallable, and will be caught here.
2708 string national_significant_number;
2709 GetNationalSignificantNumber(number, &national_significant_number);
2710 return !IsNumberMatchingDesc(
2711 national_significant_number, metadata->no_international_dialling(),
2712 reg_exps_->regexp_cache_.get());
2715 } // namespace phonenumbers