forked from twcclegg/libphonenumber-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhoneNumberUtil.cs
2993 lines (2793 loc) · 162 KB
/
PhoneNumberUtil.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#nullable disable
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace PhoneNumbers
{
/// <summary>
/// Utility for international phone numbers. Functionality includes formatting, parsing and
/// validation.
/// <para>
/// If you use this library, and want to be notified about important changes, please sign up to
/// our mailing list: http://groups.google.com/group/libphonenumber-discuss/about
/// </para>
/// NOTE: A lot of methods in this class require Region Code strings.These must be provided using
/// ISO 3166-1 two-letter country-code format.These should be in upper-case. The list of the codes
/// can be found here:
/// http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm
/// <!--
/// @author Shaopeng Jia
/// @author Lara Rennie
/// -->
/// </summary>
public partial class PhoneNumberUtil
{
// The minimum and maximum length of the national significant number.
private const int MIN_LENGTH_FOR_NSN = 2;
// The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
internal const int MAX_LENGTH_FOR_NSN = 17;
// Region-code for the unknown region.
private const string UNKNOWN_REGION = "ZZ";
private const int NANPA_COUNTRY_CODE = 1;
// A mapping from a country calling code to the region codes which denote the region represented
// by that country calling code. In the case of multiple regions sharing a calling code, such as
// the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
// first.
private readonly Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap;
// The set of regions the library supports.
private readonly HashSet<string> supportedRegions;
// The set of regions that share country calling code 1.
private readonly HashSet<string> nanpaRegions;
// Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES
// below) which are not based on *area codes*. For example, in China mobile numbers start with a
// carrier indicator, and beyond that are geographically assigned: this carrier indicator is not
// considered to be an area code.
private static bool IsGeoMobileCountryWithoutMobileAreaCode(int countryCallingCode)
=> countryCallingCode is 86; // China
// Set of country calling codes that have geographically assigned mobile numbers. This may not be
// complete; we add calling codes case by case, as we find geographical mobile numbers or hear
// from user reports. Note that countries like the US, where we can't distinguish between
// fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be
// a possibly geographically-related type anyway (like FIXED_LINE).
private static bool IsGeoMobileCountry(int countryCallingCode) => countryCallingCode is
52 or // Mexico
54 or // Argentina
55 or // Brazil
62 or // Indonesia: some prefixes only (fixed CMDA wireless)
86; // China
// The PLUS_SIGN signifies the international prefix.
internal const char PLUS_SIGN = '+';
private const string STAR_SIGN = "*";
private const string RFC3966_EXTN_PREFIX = ";ext=";
private const string RFC3966_PREFIX = "tel:";
private const string RFC3966_PHONE_CONTEXT = ";phone-context=";
private const string RFC3966_ISDN_SUBADDRESS = ";isub=";
// A map that contains characters that are essential when dialing. That means any of the
// characters in this map must not be removed from a number when dialling, otherwise the call will
// not reach the intended destination.
private static char MapDiallableChar(char c) => c is >= '0' and <= '9' or '+' or '*' or '#' ? c : '\0';
// For performance reasons, amalgamate both into one map.
private static char MapAlphaPhone(char c)
{
if (c is >= '0' and <= '9')
return c;
c = (char)(c & ~' '); // convert ASCII lowercase to uppercase
return c switch
{
'A' or 'B' or 'C' => '2',
'D' or 'E' or 'F' => '3',
'G' or 'H' or 'I' => '4',
'J' or 'K' or 'L' => '5',
'M' or 'N' or 'O' => '6',
'P' or 'Q' or 'R' or 'S' => '7',
'T' or 'U' or 'V' => '8',
'W' or 'X' or 'Y' or 'Z' => '9',
_ => '\0'
};
}
// Separate map of all symbols that we wish to retain when formatting alpha numbers. This
// includes digits, ASCII letters and number grouping symbols such as "-" and " ".
private static char MapAllPlusNumberGroupingSymbols(char c)
{
if (c is >= '0' and <= '9' or >= 'A' and <= 'Z')
return c;
if (c is >= 'a' and <= 'z')
return (char)(c & ~' '); // convert ASCII lowercase to uppercase
return c switch
{
'-' or '\uFF0D' or '\u2010' or '\u2011' or '\u2012' or '\u2013' or '\u2014' or '\u2015' or '\u2212' => '-',
'/' or '\uFF0F' => '/',
' ' or '\u3000' or '\u2060' => ' ',
'.' or '\uFF0E' => '.',
_ => '\0'
};
}
private static readonly object ThisLock = new();
// Pattern that makes it easy to distinguish whether a region has a unique international dialing
// prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
// represented as a string that contains a sequence of ASCII digits. If there are multiple
// available international prefixes in a region, they will be represented as a regex string that
// always contains character(s) other than ASCII digits.
// Note this regex also includes tilde, which signals waiting for the tone.
#if NET7_0_OR_GREATER
[GeneratedRegex("^(?>\\d+)([~\u2053\u223C\uFF5E]\\d+)?$", InternalRegexOptions.Default | RegexOptions.ExplicitCapture)]
private static partial Regex UniqueInternationalPrefix();
#else
private static readonly Regex _uniqueInternationalPrefix = new("^\\d+([~\u2053\u223C\uFF5E]\\d+)?$", InternalRegexOptions.Default | RegexOptions.ExplicitCapture);
private static Regex UniqueInternationalPrefix() => _uniqueInternationalPrefix;
#endif
// Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
// found as a leading character only.
// This consists of dash characters, white space characters, full stops, slashes,
// square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
// placeholder for carrier information in some phone numbers. Full-width variants are also
// present.
internal const string VALID_PUNCTUATION = "\\-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
"\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
// We accept alpha characters in phone numbers, ASCII only, upper and lower case.
private const string VALID_ALPHA = "A-Za-z";
internal const string PLUS_CHARS = "+\uFF0B";
internal static bool IsPlusChar(char c) => c is '+' or '\uFF0B';
#if NET7_0_OR_GREATER
[GeneratedRegex("[" + VALID_PUNCTUATION + "]+", InternalRegexOptions.Default)]
private static partial Regex SeparatorPattern();
#else
private static readonly Regex _separatorPattern = new("[" + VALID_PUNCTUATION + "]+", InternalRegexOptions.Default);
private static Regex SeparatorPattern() => _separatorPattern;
#endif
[Obsolete("This is an internal implementation detail not meant for public use", error: true), EditorBrowsable(EditorBrowsableState.Never)]
public static readonly Regex ValidStartCharPattern;
// We use this pattern to check if the phone number has at least three letters in it - if so, then
// we treat it as a number where some phone-number digits are represented by letters.
private static bool IsValidAlphaPhone(StringBuilder number)
{
for (int alpha = 0, i = 0; i < number.Length; i++)
{
var lower = number[i] | 0x20;
if ((uint)(lower - 'a') <= 'z' - 'a' && ++alpha == 3)
return true;
}
return false;
}
// Default extension prefix to use when formatting. This will be put in front of any extension
// component of the number, after the main national number is formatted. For example, if you wish
// the default extension formatting to be " extn: 3456", then you should specify " extn: " here
// as the default extension prefix. This can be overridden by region-specific preferences.
private const string DEFAULT_EXTN_PREFIX = " ext. ";
private const string ALPHANUM = VALID_ALPHA + "\\d";
private const string RFC3966_DOMAINLABEL = "(?>[" + ALPHANUM + "]+)(?>(-+[" + ALPHANUM + "])*)";
private const string RFC3966_TOPLABEL = "(?>[" + VALID_ALPHA + "]+)(?>(-*[" + ALPHANUM + "])*)";
// Regular expression of valid global-number-digits or domainname for the phone-context parameter, following the syntax defined in RFC3966.
#if NET7_0_OR_GREATER
[GeneratedRegex(@"^(\+[-.()]*\d[\d-.()]*$|(?>(" + RFC3966_DOMAINLABEL + "\\.(?!$))*)" + RFC3966_TOPLABEL + "\\.?$)", InternalRegexOptions.Default | RegexOptions.ExplicitCapture)]
private static partial Regex RFC3966_GLOBAL_NUMBER_DIGITS_OR_DOMAINNAME();
#else
// RFC3966_DOMAINLABEL is matched non-atomically on older platforms due to bugs in the regex engine.
private static readonly Regex _RFC3966_GLOBAL_NUMBER_DIGITS_OR_DOMAINNAME
= new(@"^(\+[-.()]*\d[\d-.()]*$|(" + RFC3966_DOMAINLABEL + "\\.)*" + RFC3966_TOPLABEL + "\\.?$)", InternalRegexOptions.Default | RegexOptions.ExplicitCapture);
private static Regex RFC3966_GLOBAL_NUMBER_DIGITS_OR_DOMAINNAME() => _RFC3966_GLOBAL_NUMBER_DIGITS_OR_DOMAINNAME;
#endif
///
/// Helper initialiser method to create the regular-expression pattern to match extensions.
/// Note that there are currently six capturing groups for the extension itself. If this number is
/// changed, MaybeStripExtension needs to be updated.
///
// Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
// case-insensitive regexp match. Wide character versions are also provided after each ASCII
// version.
// We cap the maximum length of an extension based on the ambiguity of the way the extension is
// prefixed. As per ITU, the officially allowed length for extensions is actually 40, but we
// don't support this since we haven't seen real examples and this introduces many false
// interpretations as the extension labels are not standardized.
// const int extLimitAfterExplicitLabel = 20;
private const string extLimitAfterExplicitLabelString = "(\\d{1,20})";
// const int extLimitAfterLikelyLabel = 15;
private const string extLimitAfterLikelyLabelString = "(\\d{1,15})";
// const int extLimitAfterAmbiguousChar = 9;
private const string extLimitAfterAmbiguousCharString = "(\\d{1,9})";
// const int extLimitWhenNotSure = 6;
private const string extLimitWhenNotSureString = "(\\d{1,6})";
private const string possibleSeparatorsBetweenNumberAndExtLabel = "[ \u00A0\\t,]*";
// Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
private const string possibleCharsAfterExtLabel = "[:\\.\uFF0E]?[ \u00A0\\t,-]*";
// Here the extension is called out in more explicit way, i.e mentioning it obvious patterns
// like "ext.". Canonical-equivalence doesn't seem to be an option with Android java, so we
// allow two options for representing the accented o - the character itself, and one in the
// unicode decomposed form with the combining acute accent.
private const string explicitExtLabels =
"(?>e?xt(?:ensi(?>o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|\u0434\u043E\u0431|anexo)";
// One-character symbols that can be used to indicate an extension, and less commonly used
// or more ambiguous extension labels.
private const string ambiguousExtLabels = "(?>[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)";
// When extension is not separated clearly.
private const string ambiguousSeparator = "[- ]+";
private const string rfcExtn = RFC3966_EXTN_PREFIX + extLimitAfterExplicitLabelString;
private const string explicitExtn = possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels
+ possibleCharsAfterExtLabel + extLimitAfterExplicitLabelString
+ "#?";
private const string ambiguousExtn = possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels
+ possibleCharsAfterExtLabel + extLimitAfterAmbiguousCharString + "#?";
private const string americanStyleExtnWithSuffix = ambiguousSeparator + extLimitWhenNotSureString + "#";
// The first regular expression covers RFC 3966 format, where the extension is added using
// ";ext=". The second more generic where extension is mentioned with explicit labels like
// "ext:". In both the above cases we allow more numbers in extension than any other extension
// labels. The third one captures when single character extension labels or less commonly used
// labels are used. In such cases we capture fewer extension digits in order to reduce the
// chance of falsely interpreting two numbers beside each other as a number + extension. The
// fourth one covers the special case of American numbers where the extension is written with a
// hash at the end, such as "- 503#".
internal const string ExtnPatternsForMatching = rfcExtn + "|" + explicitExtn + "|" + ambiguousExtn + "|" + americanStyleExtnWithSuffix;
// Additional pattern that is supported when parsing extensions, not when matching.
// ",," is commonly used for auto dialling the extension when connected. First comma is matched
// through possibleSeparatorsBetweenNumberAndExtLabel, so we do not repeat it here. Semi-colon
// works in Iphone and Android also to pop up a button with the extension number following.
private const string autoDiallingExtn = "(?>,,|;)" + possibleCharsAfterExtLabel + extLimitAfterLikelyLabelString;
private const string onlyCommasExtn = "(?>,+)" + possibleCharsAfterExtLabel + extLimitAfterAmbiguousCharString;
// Here the first pattern is exclusively for extension autodialling formats which are used
// when dialling and in this case we accept longer extensions. However, the second pattern
// is more liberal on the number of commas that acts as extension labels, so we have a strict
// cap on the number of digits in such extensions.
private const string ExtnPatternsForParsing = rfcExtn + "$|" + explicitExtn + "$|" + ambiguousExtn + "$|" + americanStyleExtnWithSuffix
+ "$|[ \u00A0\\t]*(?>" + autoDiallingExtn + "|" + onlyCommasExtn + ")#?$";
// Regexp of all known extension prefixes used by different regions followed by 1 or more valid
// digits, for use when parsing.
#if NET7_0_OR_GREATER
[GeneratedRegex(ExtnPatternsForParsing, InternalRegexOptions.Default | RegexOptions.IgnoreCase)]
internal static partial Regex ExtnPattern();
#else
private static readonly Regex _extnPattern = new(ExtnPatternsForParsing, InternalRegexOptions.Default | RegexOptions.IgnoreCase);
internal static Regex ExtnPattern() => _extnPattern;
#endif
#if NET7_0_OR_GREATER
[GeneratedRegex("\\D+", InternalRegexOptions.Default)]
internal static partial Regex NonDigitsPattern();
#else
private static readonly Regex _nonDigitsPattern = new("\\D+", InternalRegexOptions.Default);
internal static Regex NonDigitsPattern() => _nonDigitsPattern;
#endif
// The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
// first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
// correctly. Therefore, we use \d, so that the first group actually used in the pattern will be
// matched.
#if NET7_0_OR_GREATER
[GeneratedRegex("(\\$[0-9])", InternalRegexOptions.Default)]
internal static partial Regex FirstGroupPattern();
#else
private static readonly Regex _firstGroupPattern = new("(\\$[0-9])", InternalRegexOptions.Default);
internal static Regex FirstGroupPattern() => _firstGroupPattern;
#endif
// Constants used in the formatting rules to represent the national prefix, first group and
// carrier code respectively.
private const string NpPattern = "$NP";
private const string FgPattern = "$FG";
private const string CcPattern = "$CC";
// Regular expression of viable phone numbers. This is location independent. Checks we have at
// least three leading digits, and only valid punctuation, alpha characters and
// digits in the phone number. Does not include extension data.
// The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
// carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
// the start.
// Corresponds to the following:
// [digits]{minLengthNsn}|
// plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
//
// The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
// as "15" etc, but only if there is no punctuation in them. The second expression restricts the
// number of digits to three or more, but then allows them to be in international form, and to
// have alpha-characters and punctuation.
// We append optionally the extension pattern to the end here, as a valid phone number may
// have an extension prefix appended, followed by 1 or more digits.
private const string ValidPhoneNumberPattern = "^(\\d{2}$|" +
"[" + PLUS_CHARS + "]*([" + VALID_PUNCTUATION + STAR_SIGN + "]*\\d){3}[" +
VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + "\\d]*($|" + ExtnPatternsForParsing + "))";
#if NET7_0_OR_GREATER
[GeneratedRegex(ValidPhoneNumberPattern, InternalRegexOptions.Default | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture)]
internal static partial Regex ValidPhoneNumber();
#else
private static readonly Regex _validPhoneNumber = new(ValidPhoneNumberPattern, InternalRegexOptions.Default | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
internal static Regex ValidPhoneNumber() => _validPhoneNumber;
#endif
private static PhoneNumberUtil instance;
// A mapping from a region code to the PhoneMetadata for that region.
private readonly Dictionary<string, PhoneMetadata> regionToMetadataMap;
// A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
// that country calling code. Examples of the country calling codes include 800 (International
// Toll Free Service) and 808 (International Shared Cost Service).
private readonly Dictionary<int, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
new Dictionary<int, PhoneMetadata>();
public const string REGION_CODE_FOR_NON_GEO_ENTITY = "001";
/// <summary>Types of phone number matches. See detailed description beside the isNumberMatch() method.</summary>
public enum MatchType
{
#pragma warning disable 1591
NOT_A_NUMBER,
NO_MATCH,
SHORT_NSN_MATCH,
NSN_MATCH,
EXACT_MATCH
#pragma warning restore 1591
}
/// <summary>Possible outcomes when testing if a PhoneNumber is possible.</summary>
public enum ValidationResult
{
/// <summary>The number length matches that of valid numbers for this region.</summary>
IS_POSSIBLE,
/// <summary>
/// The number length matches that of local numbers for this region only (i.e. numbers that may
/// be able to be dialled within an area, but do not have all the information to be dialled from
/// anywhere inside or outside the country).
/// </summary>
IS_POSSIBLE_LOCAL_ONLY,
/// <summary>The number has an invalid country calling code.</summary>
INVALID_COUNTRY_CODE,
/// <summary>The number is shorter than all valid numbers for this region.</summary>
TOO_SHORT,
/// <summary>
/// The number is longer than the shortest valid numbers for this region, shorter than the
/// longest valid numbers for this region, and does not itself have a number length that matches
/// valid numbers for this region. This can also be returned in the case where
/// isPossibleNumberForTypeWithReason was called, and there are no numbers of this type at all
/// for this region.
/// </summary>
INVALID_LENGTH,
/// <summary>The number is longer than all valid numbers for this region.</summary>
TOO_LONG
}
/// <summary>
/// Leniency when <see cref="FindNumbers(string, string)"/> finding potential phone numbers in text
/// segments. The levels here are ordered in increasing strictness.
/// </summary>
public enum Leniency
{
/// <summary>
/// Phone numbers accepted are <see cref="IsPossibleNumber(PhoneNumber)"/>
/// possible, but not necessarily <see cref="IsValidNumber(PhoneNumber)"/> valid.
/// </summary>
POSSIBLE,
/// <summary>
/// Phone numbers accepted are <see cref="IsPossibleNumber(PhoneNumber)"/>
/// possible and <see cref="IsValidNumber(PhoneNumber)"/> valid. Numbers written
/// in national format must have their national-prefix present if it is usually written for a
/// number of this type.
/// </summary>
VALID,
/// <summary>
/// Phone numbers accepted are <see cref="IsValidNumber(PhoneNumber)"/> valid and
/// are grouped in a possible way for this locale. For example, a US number written as
/// "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
/// "650 253 0000", "650 2530000" or "6502530000" are.
/// Numbers with more than one '/' symbol are also dropped at this level.
/// <para>
/// Warning: This level might result in lower coverage especially for regions outside of country
/// code "+1". If you are not sure about which level to use, email the discussion group
/// [email protected].
/// </para>
/// </summary>
STRICT_GROUPING,
/// <summary>
/// Phone numbers accepted are <see cref="IsValidNumber(PhoneNumber)"/> valid and
/// are grouped in the same way that we would have formatted it, or as a single block. For
/// example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
/// "650 253 0000" or "6502530000" are.
/// Numbers with more than one '/' symbol are also dropped at this level.
/// <para>
/// Warning: This level might result in lower coverage especially for regions outside of country
/// code "+1". If you are not sure about which level to use, email the discussion group
/// [email protected].
/// </para>
/// </summary>
EXACT_GROUPING
}
public bool Verify(
Leniency leniency,
PhoneNumber number,
string candidate,
PhoneNumberUtil util,
PhoneNumberMatcher matcher)
{
switch (leniency)
{
case Leniency.POSSIBLE:
return IsPossibleNumber(number);
case Leniency.VALID:
{
if (!util.IsValidNumber(number) ||
!PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util))
return false;
return PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util);
}
case Leniency.STRICT_GROUPING:
{
if (!util.IsValidNumber(number) ||
!PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util) ||
PhoneNumberMatcher.ContainsMoreThanOneSlash(candidate) ||
!PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util))
{
return false;
}
return matcher.CheckNumberGroupingIsValid(
number, candidate, util, PhoneNumberMatcher.AllNumberGroupsRemainGrouped);
}
case Leniency.EXACT_GROUPING:
{
if (!util.IsValidNumber(number) ||
!PhoneNumberMatcher.ContainsOnlyValidXChars(number, candidate, util) ||
PhoneNumberMatcher.ContainsMoreThanOneSlash(candidate) ||
!PhoneNumberMatcher.IsNationalPrefixPresentIfRequired(number, util))
{
return false;
}
return matcher.CheckNumberGroupingIsValid(
number, candidate, util, PhoneNumberMatcher.AllNumberGroupsAreExactlyPresent);
}
default:
throw new ArgumentOutOfRangeException(nameof(leniency), leniency, null);
}
}
internal PhoneNumberUtil(string baseFileLocation, Assembly asm = null,
Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap = null) : this(
BuildMetadataFromXml.GetStream(baseFileLocation, asm), countryCallingCodeToRegionCodeMap)
{
}
internal PhoneNumberUtil(Stream metaDataStream, Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap = null)
{
var phoneMetadata = BuildMetadataFromXml.BuildPhoneMetadataFromStream(metaDataStream);
this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap ??=
BuildMetadataFromXml.BuildCountryCodeToRegionCodeMap(phoneMetadata);
#if NET6_0_OR_GREATER
supportedRegions = new HashSet<string>(280); // currently 245 items
#else
supportedRegions = new HashSet<string>();
#endif
foreach (var regionCodes in countryCallingCodeToRegionCodeMap)
supportedRegions.UnionWith(regionCodes.Value);
supportedRegions.Remove(REGION_CODE_FOR_NON_GEO_ENTITY);
nanpaRegions = countryCallingCodeToRegionCodeMap.TryGetValue(NANPA_COUNTRY_CODE, out var regions) ? new(regions) : new();
regionToMetadataMap = new Dictionary<string, PhoneMetadata>(280); // currently 245 items
foreach (var m in phoneMetadata)
{
countryCodeToNonGeographicalMetadataMap[m.CountryCode] = m;
regionToMetadataMap[m.Id] = m;
}
regionToMetadataMap.Remove(REGION_CODE_FOR_NON_GEO_ENTITY);
}
/// <summary>
/// Attempts to extract a possible number from the string passed in. This currently strips all
/// leading characters that cannot be used to start a phone number. Characters that can be used to
/// start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
/// are found in the number passed in, an empty string is returned. This function also attempts to
/// strip off any alternative extensions or endings if two or more are present, such as in the case
/// of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
/// (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
/// number is parsed correctly.
/// </summary>
/// <param name="number">The string that might contain a phone number.</param>
/// <returns>The number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
/// string if no character used to start phone numbers (such as + or any digit) is
/// found in the number.</returns>
public static string ExtractPossibleNumber(string number)
{
for (int i = 0; i < number.Length; i++)
{
if (IsPlusChar(number[i]) || char.IsDigit(number[i]))
{
if (i > 0) number = number.Substring(i);
// Remove trailing non-alpha non-numerical characters.
number = PhoneNumberMatcher.TrimAfterUnwantedChars(number);
// Check for extra numbers at the end.
return PhoneNumberMatcher.TrimAfterSecondNumberStart(number);
}
}
return "";
}
/// <summary>
/// Checks to see if the string of characters could possibly be a phone number at all. At the
/// moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
/// commonly found in phone numbers.
/// This method does not require the number to be normalized in advance - but does assume that
/// leading non-number symbols have been removed, such as by the method extractPossibleNumber.
/// </summary>
/// <param name="number">String to be checked for viability as a phone number.</param>
/// <returns>True if the number could be a phone number of some sort, otherwise false.</returns>
public static bool IsViablePhoneNumber(string number)
{
if (number.Length < MIN_LENGTH_FOR_NSN)
return false;
return ValidPhoneNumber().IsMatch(number);
}
private static void Normalize(StringBuilder number)
{
if (IsValidAlphaPhone(number))
{
NormalizeHelper(number, MapAlphaPhone, true);
}
else
{
NormalizeDigits(number, false);
}
}
internal static StringBuilder NormalizeDigits(StringBuilder number, bool keepNonDigits)
{
int pos = 0;
for (int i = 0; i < number.Length; i++)
{
var c = number[i];
if ((uint)(c - '0') <= 9)
{
number[pos++] = c;
}
else
{
var digit = (int)char.GetNumericValue(c);
if (digit != -1)
{
var size = number.Length;
number.Insert(pos, digit);
size = number.Length - size;
pos += size;
i += size;
}
else if (keepNonDigits)
{
number[pos++] = c;
}
}
}
number.Length = pos;
return number;
}
/// <summary>
/// Gets the length of the geographical area code from the
/// PhoneNumber object passed in, so that clients could use it
/// to split a national significant number into geographical area code and subscriber number. It
/// works in such a way that the resultant subscriber number should be diallable, at least on some
/// devices. An example of how this could be used:
///
/// <code>
/// var phoneUtil = PhoneNumberUtil.getInstance();
/// var number = phoneUtil.parse("16502530000", "US");
/// var nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
/// string areaCode;
/// string subscriberNumber;
///
/// var areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
/// if (areaCodeLength > 0)
/// {
/// areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
/// subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
/// }
/// else {
/// areaCode = "";
/// subscriberNumber = nationalSignificantNumber;
/// }
/// </code>
///
/// N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
/// using it for most purposes, but recommends using the more general <c>NationalNumber</c>
/// instead. Read the following carefully before deciding to use this method:
/// <ul>
/// <li> geographical area codes change over time, and this method honors those changes;
/// therefore, it doesn't guarantee the stability of the result it produces.</li>
/// <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
/// typically requires the full NationalNumber to be dialled in most regions).</li>
/// <li> most non-geographical numbers have no area codes, including numbers from non-geographical
/// entities</li>
/// <li> some geographical numbers have no area codes.</li>
/// </ul>
/// </summary>
///
/// <param name="number">the PhoneNumber object for which clients want to know the length of the area code</param>
/// <returns>the length of area code of the PhoneNumber object passed in</returns>
public int GetLengthOfGeographicalAreaCode(PhoneNumber number)
{
var regionCode = GetRegionCodeForNumber(number);
if (!IsValidRegionCode(regionCode))
return 0;
var metadata = GetMetadataForRegion(regionCode);
// If a country doesn't use a national prefix, and this number doesn't have an Italian leading
// zero, we assume it is a closed dialling plan with no area codes.
if (!metadata.HasNationalPrefix && !number.HasNumberOfLeadingZeros)
return 0;
var type = GetNumberType(number);
var countryCallingCode = number.CountryCode;
if (type == PhoneNumberType.MOBILE
// Note this is a rough heuristic; it doesn't cover Indonesia well, for example, where area
// codes are present for some mobile phones but not for others. We have no better way of
// representing this in the metadata at this point.
&& IsGeoMobileCountryWithoutMobileAreaCode(countryCallingCode))
{
return 0;
}
if (!IsNumberGeographical(type, countryCallingCode))
{
return 0;
}
return GetLengthOfNationalDestinationCode(number);
}
/// <summary>
/// Gets the length of the national destination code (NDC) from the
/// PhoneNumber object passed in, so that clients could use it
/// to split a national significant number into NDC and subscriber number. The NDC of a phone
/// number is normally the first group of digit(s) right after the country calling code when the
/// number is formatted in the international format, if there is a subscriber number part that
/// follows.
///
/// N.B.: similar to an area code, not all numbers have an NDC!
///
/// An example of how this could be used:
///
/// <code>
/// var phoneUtil = PhoneNumberUtil.getInstance();
/// var number = phoneUtil.parse("18002530000", "US");
/// var nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
/// string nationalDestinationCode;
/// string subscriberNumber;
///
/// var nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
/// if (nationalDestinationCodeLength > 0)
/// {
/// nationalDestinationCode = nationalSignificantNumber.substring(0,
/// nationalDestinationCodeLength);
/// subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
/// }
/// else
/// {
/// nationalDestinationCode = "";
/// subscriberNumber = nationalSignificantNumber;
/// }
/// </code>
///
/// Refer to the unit tests to see the difference between this function and
/// <see cref="GetLengthOfGeographicalAreaCode" />.
/// </summary>
///
/// <param name="number"> the PhoneNumber object for which clients want to know the length of the NDC.</param>
/// <returns> the length of NDC of the PhoneNumber object passed in, which could be zero</returns>
public int GetLengthOfNationalDestinationCode(PhoneNumber number)
{
PhoneNumber copiedProto;
if (number.HasExtension)
{
// We don't want to alter the proto given to us, but we don't want to include the extension
// when we format it, so we copy it and clear the extension here.
copiedProto = number.Clone();
copiedProto.Extension = "";
}
else
{
copiedProto = number;
}
var nationalSignificantNumber = Format(copiedProto, PhoneNumberFormat.INTERNATIONAL);
var numberGroups = NonDigitsPattern().Split(nationalSignificantNumber, 5);
// The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
// string (before the + symbol) and the second group will be the country calling code. The third
// group will be area code if it is not the last group.
if (numberGroups.Length <= 3)
return 0;
if (GetNumberType(number) == PhoneNumberType.MOBILE)
{
// For example Argentinian mobile numbers, when formatted in the international format, are in
// the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
// add the length of the second group (which is the mobile token), which also forms part of
// the national significant number. This assumes that the mobile token is always formatted
// separately from the rest of the phone number.
var mobileToken = GetCountryMobileToken(number.CountryCode);
if (!mobileToken.Equals(""))
{
return numberGroups[2].Length + numberGroups[3].Length;
}
}
return numberGroups[2].Length;
}
/// <summary>
/// Returns the mobile token for the provided country calling code if it has one, otherwise
/// returns an empty string. A mobile token is a number inserted before the area code when dialing
/// a mobile number from that country from abroad.
/// </summary>
/// <param name="countryCallingCode">The country calling code for which we want the mobile token.</param>
/// <returns>The mobile token, as a string, for the given country calling code.</returns>
public static string GetCountryMobileToken(int countryCallingCode)
{
// Map of country calling codes that use a mobile token before the area code. One example of when
// this is relevant is when determining the length of the national destination code, which should
// be the length of the area code plus the length of the mobile token.
return countryCallingCode switch
{
52 => "1",
54 => "9",
_ => ""
};
}
/// <summary>
/// Normalizes a string of characters representing a phone number by replacing all characters found
/// in the accompanying map with the values therein, and stripping all other characters if
/// removeNonMatches is true.
/// </summary>
/// <param name="number">A string of characters representing a phone number.</param>
/// <param name="normalizationReplacements">A mapping of characters to what they should be replaced by in
/// the normalized version of the phone number.</param>
/// <param name="removeNonMatches">indicates whether characters that are not able to be replaced
/// should be stripped from the number. If this is false, they
/// will be left unchanged in the number.</param>
/// <returns>The normalized string version of the phone number.</returns>
private static string NormalizeHelper(string number, Func<char, char> normalizationReplacements, bool removeNonMatches)
=> NormalizeHelper(new StringBuilder(number), normalizationReplacements, removeNonMatches).ToString();
private static StringBuilder NormalizeHelper(StringBuilder number, Func<char, char> normalizationReplacements, bool removeNonMatches)
{
int pos = 0;
for (int i = 0; i < number.Length; i++)
{
var character = number[i];
if (normalizationReplacements(character) is > '\0' and var newDigit)
number[pos++] = newDigit;
else if (!removeNonMatches)
number[pos++] = character;
// If neither of the above are true, we remove this character.
}
number.Length = pos;
return number;
}
/// <summary>
/// Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
/// parsing, or validation. The instance is loaded with all phone number metadata.
/// The <see cref="PhoneNumberUtil" /> is implemented as a singleton.Therefore, calling getInstance
/// multiple times will only result in one instance being created.
/// </summary>
/// <returns> a PhoneNumberUtil instance</returns>
public static PhoneNumberUtil GetInstance(string baseFileLocation,
Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap = null)
{
lock (ThisLock)
return instance ??= new PhoneNumberUtil(baseFileLocation, null, countryCallingCodeToRegionCodeMap);
}
/// <summary>
/// Create a new {@link PhoneNumberUtil} instance to carry out international phone number formatting, parsing,
/// or validation. The instance is loaded with all metadata by using the metadataLoader specified.
/// <p>This method should only be used in the rare case in which you want to manage your own metadata loading.
/// Calling this method multiple times is very expensive, as each time a new instance is created from scratch.
/// When in doubt, use {@link #getInstance}.
/// </p>
/// </summary>
/// <param name="metadataStream">Stream of new metadata</param>
/// <returns>a PhoneNumberUtil instance</returns>
public static PhoneNumberUtil CreateInstance(Stream metadataStream)
{
return new PhoneNumberUtil(metadataStream);
}
/// <summary>
/// Returns all regions the library has metadata for.
/// </summary>
/// <returns>An unordered set of the two-letter region codes for every geographical region the
/// library supports.</returns>
public HashSet<string> GetSupportedRegions()
{
return supportedRegions;
}
/// <summary>
/// Returns all global network calling codes the library has metadata for.
/// </summary>
/// <returns>An unordered set of the country calling codes for every non-geographical entity the
/// library supports.</returns>
public Dictionary<int, PhoneMetadata>.KeyCollection GetSupportedGlobalNetworkCallingCodes()
{
return countryCodeToNonGeographicalMetadataMap.Keys;
}
/// <summary>
/// Returns all country calling codes the library has metadata for, covering both non-geographical
/// entities (global network calling codes) and those used for geographical entities. This could be
/// used to populate a drop-down box of country calling codes for a phone-number widget, for
/// instance.
/// </summary>
/// <returns>An unordered set of the country calling codes for every geographical and
/// non-geographical entity the library supports.</returns>
public HashSet<int> GetSupportedCallingCodes()
{
return new HashSet<int>(countryCallingCodeToRegionCodeMap.Keys);
}
/// <summary>
/// Returns true if there is any possible number data set for a particular PhoneNumberDesc.
/// </summary>
/// <param name="desc"></param>
/// <returns></returns>
private static bool DescHasPossibleNumberData(PhoneNumberDesc desc)
{
// If this is empty, it means numbers of this type inherit from the "general desc" -> the value
// "-1" means that no numbers exist for this type.
return desc.PossibleLengthCount != 1 || desc.GetPossibleLength(0) != -1;
}
/// <summary>
/// Returns true if there is any data set for a particular PhoneNumberDesc.
/// </summary>
/// <param name="desc"></param>
/// <returns></returns>
private static bool DescHasData(PhoneNumberDesc desc)
{
// Checking most properties since we don't know what's present, since a custom build may have
// stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the
// possibleLengthsLocalOnly, since if this is the only thing that's present we don't really
// support the type at all: no type-specific methods will work with only this data.
return desc.HasExampleNumber
|| DescHasPossibleNumberData(desc)
|| desc.HasNationalNumberPattern;
}
/// <summary>
/// Returns the types we have metadata for based on the PhoneMetadata object passed in, which must
/// be non-null.
/// </summary>
/// <param name="metadata"></param>
/// <returns></returns>
private HashSet<PhoneNumberType> GetSupportedTypesForMetadata(PhoneMetadata metadata)
{
var types = new HashSet<PhoneNumberType>();
foreach (PhoneNumberType type in Enum.GetValues(typeof(PhoneNumberType)))
{
if (type == PhoneNumberType.FIXED_LINE_OR_MOBILE || type == PhoneNumberType.UNKNOWN)
{
// Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a
// particular number type can't be determined) or UNKNOWN (the non-type).
continue;
}
if (DescHasData(GetNumberDescByType(metadata, type)))
{
types.Add(type);
}
}
return types;
}
/// <summary>
/// Returns the types for a given region which the library has metadata for. Will not include
/// FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE,
/// both FIXED_LINE and MOBILE would be present) and UNKNOWN.
///
/// No types will be returned for invalid or unknown region codes.
/// </summary>
/// <param name="regionCode"></param>
/// <returns></returns>
public HashSet<PhoneNumberType> GetSupportedTypesForRegion(string regionCode)
{
if (!IsValidRegionCode(regionCode))
{
return new HashSet<PhoneNumberType>();
}
var metadata = GetMetadataForRegion(regionCode);
return GetSupportedTypesForMetadata(metadata);
}
/// <summary>
/// Returns the types for a country-code belonging to a non-geographical entity which the library
/// has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical
/// entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be
/// present) and UNKNOWN.
///
/// No types will be returned for country calling codes that do not map to a known non-geographical
/// entity.
/// </summary>
/// <param name="countryCallingCode"></param>
/// <returns></returns>
public HashSet<PhoneNumberType> GetSupportedTypesForNonGeoEntity(int countryCallingCode)
{
var metadata = GetMetadataForNonGeographicalRegion(countryCallingCode);
return metadata == null ? new HashSet<PhoneNumberType>() : GetSupportedTypesForMetadata(metadata);
}
/// <summary>
/// Gets a <see cref="PhoneNumberUtil"/> instance to carry out international phone number formatting,
/// parsing, or validation. The instance is loaded with phone number metadata for a number of most
/// commonly used regions.
/// <para>
/// The <see cref="PhoneNumberUtil"/> is implemented as a singleton. Therefore, calling getInstance
/// multiple times will only result in one instance being created.
/// </para>
/// </summary>
/// <returns>A <see cref="PhoneNumberUtil"/> instance.</returns>
public static PhoneNumberUtil GetInstance() => instance ?? GetInstance("PhoneNumberMetadata.xml");
/// <summary>
/// Tests whether a phone number has a geographical association. It checks if the number is
/// associated with a certain region in the country to which it belongs. Note that this doesn't
/// verify if the number is actually in use.
/// </summary>
/// <param name="phoneNumber"></param>
/// <returns></returns>
public bool IsNumberGeographical(PhoneNumber phoneNumber)
{
return IsNumberGeographical(GetNumberType(phoneNumber), phoneNumber.CountryCode);
}
/// <summary>
/// Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type is
/// expensive; if we have already done this, we don't want to do it again.
/// </summary>
/// <param name="phoneNumberType"></param>
/// <param name="countryCallingCode"></param>
/// <returns></returns>
public bool IsNumberGeographical(PhoneNumberType phoneNumberType, int countryCallingCode)
{