-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathphonenumberutil.go
More file actions
3166 lines (2940 loc) · 125 KB
/
Copy pathphonenumberutil.go
File metadata and controls
3166 lines (2940 loc) · 125 KB
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
// Port of java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java.
package phonenumbers
import (
"errors"
"iter"
"math"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/nyaruka/phonenumbers/v2/internal/regexcache"
"github.com/nyaruka/phonenumbers/v2/internal/stringbuilder"
"github.com/nyaruka/phonenumbers/v2/metadata"
"google.golang.org/protobuf/proto"
)
const (
// minLengthForNSN is the minimum and maximum length of the national significant number.
minLengthForNSN = 2
// maxLengthForNSN: The ITU says the maximum length should be 15, but we have
// found longer numbers in Germany.
maxLengthForNSN = 17
// maxLengthCountryCode is the maximum length of the country calling code.
maxLengthCountryCode = 3
// maxInputStringLength caps input strings for parsing at 250 chars.
// This prevents malicious input from overflowing the regular-expression
// engine.
maxInputStringLength = 250
// unknownRegion is the region-code for the unknown region.
unknownRegion = "ZZ"
nanpaCountryCode = 1
// The plusSign signifies the international prefix.
plusSign = '+'
starSign = '*'
rfc3966ExtnPrefix = ";ext="
rfc3966Prefix = "tel:"
rfc3966PhoneContext = ";phone-context="
rfc3966IsdnSubaddress = ";isub="
// 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.
validPunctuation = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
"\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D." +
"\\[\\]/~\u2053\u223C\uFF5E"
digitsClass = "\\p{Nd}"
// We accept alpha characters in phone numbers, ASCII only, upper
// and lower case.
validAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
plusChars = "+\uFF0B"
)
var (
// 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.
mobileTokenMappings = map[int]string{
54: "9",
}
// A map that contains characters that are essential when dialling.
// 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.
diallableCharMappings = map[rune]rune{
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
'7': '7',
'8': '8',
'9': '9',
'0': '0',
plusSign: plusSign,
'*': '*',
'#': '#',
}
// Combined map of digit and alpha (letter to digit) mappings, used to
// convert alpha characters in a phone number to their dialpad digits.
alphaPhoneMappings = map[rune]rune{
'0': '0',
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
'7': '7',
'8': '8',
'9': '9',
'A': '2',
'B': '2',
'C': '2',
'D': '3',
'E': '3',
'F': '3',
'G': '4',
'H': '4',
'I': '4',
'J': '5',
'K': '5',
'L': '5',
'M': '6',
'N': '6',
'O': '6',
'P': '7',
'Q': '7',
'R': '7',
'S': '7',
'T': '8',
'U': '8',
'V': '8',
'W': '9',
'X': '9',
'Y': '9',
'Z': '9',
}
// 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 " ".
allPlusNumberGroupingSymbols = map[rune]rune{
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
'7': '7',
'8': '8',
'9': '9',
'0': '0',
plusSign: plusSign,
'*': '*',
'A': 'A',
'B': 'B',
'C': 'C',
'D': 'D',
'E': 'E',
'F': 'F',
'G': 'G',
'H': 'H',
'I': 'I',
'J': 'J',
'K': 'K',
'L': 'L',
'M': 'M',
'N': 'N',
'O': 'O',
'P': 'P',
'Q': 'Q',
'R': 'R',
'S': 'S',
'T': 'T',
'U': 'U',
'V': 'V',
'W': 'W',
'X': 'X',
'Y': 'Y',
'Z': 'Z',
'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L',
'm': 'M',
'n': 'N',
'o': 'O',
'p': 'P',
'q': 'Q',
'r': 'R',
's': 'S',
't': 'T',
'u': 'U',
'v': 'V',
'w': 'W',
'x': 'X',
'y': 'Y',
'z': 'Z',
'-': '-',
'\uFF0D': '-',
'\u2010': '-',
'\u2011': '-',
'\u2012': '-',
'\u2013': '-',
'\u2014': '-',
'\u2015': '-',
'\u2212': '-',
'/': '/',
'\uFF0F': '/',
' ': ' ',
'\u3000': ' ',
'\u2060': ' ',
'.': '.',
'\uFF0E': '.',
}
// 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.
// Anchored to require a full match, mirroring Java's Pattern.matches(): Go's
// MatchString is a partial (unanchored) match, which would wrongly treat a
// regex IDD prefix like "0[0-3][0-9]" as a unique prefix (matching its leading
// "0") instead of falling back to international "+" formatting.
uniqueInternationalPrefix = regexp.MustCompile("^(?:[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?)$")
plusCharsPattern = regexp.MustCompile("[" + plusChars + "]+")
separatorPattern = regexp.MustCompile("[" + validPunctuation + "]+")
notSeparatorPattern = regexp.MustCompile("[^" + validPunctuation + "]+")
capturingDigitPattern = regexp.MustCompile("(" + digitsClass + ")")
// Regular expression of acceptable characters that may start a
// phone number for the purposes of parsing. This allows us to
// strip away meaningless prefixes to phone numbers that may be
// mistakenly given to us. This consists of digits, the plus symbol
// and arabic-indic digits. This does not contain alpha characters,
// although they may be used later in the number. It also does not
// include other punctuation, as this will be stripped later during
// parsing and is of no information value when parsing a number.
validStartChar = "[" + plusChars + digitsClass + "]"
validStartCharPattern = regexp.MustCompile(validStartChar)
// Regular expression of characters typically used to start a second
// phone number for the purposes of parsing. This allows us to strip
// off parts of the number that are actually the start of another
// number, such as for: (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.
secondNumberStart = "[\\\\/] *x"
secondNumberStartPattern = regexp.MustCompile(secondNumberStart)
// Regular expression of trailing characters that we want to remove.
// We remove all characters that are not alpha or numerical characters.
// The hash character is retained here, as it may signify the previous
// block was an extension.
unwantedEndChars = "[^\\p{N}\\p{L}#]+$"
unwantedEndCharPattern = regexp.MustCompile(unwantedEndChars)
// 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.
validAlphaPhonePattern = regexp.MustCompile("^(?:.*?[A-Za-z]){3}.*$")
// 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.
//
// Note validPunctuation starts with a -, so must be the first in the range.
validPhoneNumber = digitsClass + "{" + strconv.Itoa(minLengthForNSN) + "}" + "|" +
"[" + plusChars + "]*(?:[" + validPunctuation + string(starSign) +
"]*" + digitsClass + "){3,}[" +
validPunctuation + string(starSign) + validAlpha + digitsClass + "]*"
// 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.
defaultExtnPrefix = " ext. "
// 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.
possibleSeparatorsBetweenNumberAndExtLabel = "[ \u00A0\\t,]*"
// Optional full stop (.) or colon, followed by zero or more spaces/tabs/commas.
possibleCharsAfterExtLabel = "[:\\.\uFF0E]?[ \u00A0\\t,-]*"
optionalExtnSuffix = "#?"
// Here the extension is called out in a more explicit way, i.e.
// mentioning it with 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.
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.
ambiguousExtLabels = "(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)"
ambiguousSeparator = "[- ]+"
// Regexp of all possible ways to write extensions, for use when
// parsing. This will be run as a case-insensitive regexp match.
// maybeStripExtension iterates over all submatches of this pattern
// and assumes that every capturing group corresponds to the
// extension digits. When modifying this regexp, ensure that any
// non-extension grouping uses non-capturing groups (?:...) so as
// not to introduce additional capturing groups that would break
// extension parsing.
//
// The first regular expression covers RFC 3966 format, where the
// extension is added using ";ext=". The second is a more generic
// expression where the extension is mentioned with explicit labels like "ext:". In both
// cases we allow more digits. The third captures when single
// character extension labels or less commonly used labels are used,
// with fewer extension digits to reduce false positives. The fourth
// covers American numbers where the extension is written with a
// hash at the end, such as "- 503#".
extnPatternsForMatching = rfc3966ExtnPrefix + "(" + digitsClass + "{1,20})" + "|" +
possibleSeparatorsBetweenNumberAndExtLabel + explicitExtLabels +
possibleCharsAfterExtLabel + "(" + digitsClass + "{1,20})" + optionalExtnSuffix + "|" +
possibleSeparatorsBetweenNumberAndExtLabel + ambiguousExtLabels +
possibleCharsAfterExtLabel + "(" + digitsClass + "{1,9})" + optionalExtnSuffix + "|" +
ambiguousSeparator + "(" + digitsClass + "{1,6})#"
// Additional patterns supported when parsing extensions, not when matching.
// ",," is commonly used for auto dialling the extension when connected.
// Semi-colon works on iPhone and Android to pop up a button with the
// extension number following.
possibleSeparatorsNumberExtLabelNoComma = "[ \u00A0\\t]*"
autoDiallingAndExtLabelsFound = "(?:,{2}|;)"
extnPatternsForParsing = extnPatternsForMatching + "|" +
possibleSeparatorsNumberExtLabelNoComma + autoDiallingAndExtLabelsFound +
possibleCharsAfterExtLabel + "(" + digitsClass + "{1,15})" + optionalExtnSuffix + "|" +
possibleSeparatorsNumberExtLabelNoComma + "(?:,)+" +
possibleCharsAfterExtLabel + "(" + digitsClass + "{1,9})" + optionalExtnSuffix
// Regexp of all known extension prefixes used by different regions
// followed by 1 or more valid digits, for use when parsing.
extnPattern = regexp.MustCompile("(?i)(?:" + extnPatternsForParsing + ")$")
// 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.
validPhoneNumberPattern = regexp.MustCompile(
"(?i)^(" + validPhoneNumber + "(?:" + extnPatternsForParsing + ")?)$")
nonDigitsPattern = regexp.MustCompile(`(\D+)`)
// The firstGroupPattern 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.
firstGroupPattern = regexp.MustCompile(`(\$\d)`)
npPattern = regexp.MustCompile(`\$NP`)
fgPattern = regexp.MustCompile(`\$FG`)
ccPattern = regexp.MustCompile(`\$CC`)
// A pattern that is used to determine if the national prefix
// formatting rule has the first group only, i.e., does not start
// with the national prefix. Note that the pattern explicitly allows
// for unbalanced parentheses.
firstGroupOnlyPrefixPattern = regexp.MustCompile(`^\(?\$1\)?$`)
REGION_CODE_FOR_NON_GEO_ENTITY = "001"
// Regular expression of valid global-number-digits for the phone-context parameter, following the
// syntax defined in RFC3966.
rfc3966VisualSeparator = "[\\-\\.\\(\\)]?"
rfc3966PhoneDigit = "(" + digitsClass + "|" + rfc3966VisualSeparator + ")"
rfc3966GlobalNumberDigits = "^\\" + string(plusSign) + rfc3966PhoneDigit + "*" + digitsClass + rfc3966PhoneDigit + "*$"
rfc3966GlobalNumberDigitsPattern = regexp.MustCompile(rfc3966GlobalNumberDigits)
// Regular expression of valid domainname for the phone-context parameter, following the syntax
// defined in RFC3966.
alphanum = validAlpha + digitsClass
rfc3966Domainlabel = "[" + alphanum + "]+((\\-)*[" + alphanum + "])*"
rfc3966Toplabel = "[" + validAlpha + "]+((\\-)*[" + alphanum + "])*"
rfc3966Domainname = "^(" + rfc3966Domainlabel + "\\.)*" + rfc3966Toplabel + "\\.?$"
rfc3966DomainnamePattern = regexp.MustCompile(rfc3966Domainname)
// Set of country codes that have geographically assigned mobile numbers (see geoMobileCountries
// 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.
geoMobileCountriesWithoutMobileAreaCodes = map[int32]bool{
86: true, // China
}
// Set of country codes that doesn't have national prefix, but it has area codes.
countriesWithoutNationalPrefixWithAreaCodes = map[int32]bool{
52: true, // Mexico
}
// 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).
geoMobileCountries = map[int32]bool{
52: true, // Mexico
54: true, // Argentina
55: true, // Brazil
62: true, // Indonesia: some prefixes only (fixed CMDA wireless)
86: true, // China
}
)
// 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 validStartCharPattern. 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.
func extractPossibleNumber(number string) string {
if validStartCharPattern.MatchString(number) {
start := validStartCharPattern.FindIndex([]byte(number))[0]
number = number[start:]
// Remove trailing non-alpha non-numerical characters.
indices := unwantedEndCharPattern.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
// Check for extra numbers at the end.
indices = secondNumberStartPattern.FindIndex([]byte(number))
if len(indices) > 0 {
number = number[0:indices[0]]
}
return number
}
return ""
}
// 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.
// @VisibleForTesting
func isViablePhoneNumber(number string) bool {
if len(number) < minLengthForNSN {
return false
}
return validPhoneNumberPattern.MatchString(number)
}
// Normalizes a string of characters representing a phone number. This
// performs the following conversions:
//
// - Punctuation is stripped.
//
// - For ALPHA/VANITY numbers:
//
// - Letters are converted to their numeric representation on a telephone
// keypad. The keypad used here is the one defined in ITU Recommendation
// E.161. This is only done if there are 3 or more letters in the
// number, to lessen the risk that such letters are typos.
//
// - For other numbers:
//
// - Wide-ascii digits are converted to normal ASCII (European) digits.
//
// - Arabic-Indic numerals are converted to European numerals.
//
// - Spurious alpha characters are stripped.
func normalize(number string) string {
if validAlphaPhonePattern.MatchString(number) {
return normalizeHelper(number, alphaPhoneMappings, true)
}
return NormalizeDigitsOnly(number)
}
// Normalizes a string of characters representing a phone number. This
// converts wide-ascii and arabic-indic numerals to European numerals,
// and strips punctuation and alpha characters.
func NormalizeDigitsOnly(number string) string {
return normalizeDigits(number, false /* strip non-digits */)
}
// arabicIndicNumberals maps the various Unicode Arabic-Indic digit code points
// to their ASCII equivalents, used when normalizing digits.
var arabicIndicNumberals = map[rune]rune{
'٠': '0',
'۰': '0',
'١': '1',
'۱': '1',
'٢': '2',
'۲': '2',
'٣': '3',
'۳': '3',
'٤': '4',
'۴': '4',
'٥': '5',
'۵': '5',
'٦': '6',
'۶': '6',
'٧': '7',
'۷': '7',
'٨': '8',
'۸': '8',
'٩': '9',
'۹': '9',
'\uFF10': '0',
'\uFF11': '1',
'\uFF12': '2',
'\uFF13': '3',
'\uFF14': '4',
'\uFF15': '5',
'\uFF16': '6',
'\uFF17': '7',
'\uFF18': '8',
'\uFF19': '9',
}
func normalizeDigits(number string, keepNonDigits bool) string {
buf := number
var normalizedDigits = stringbuilder.New(nil)
for _, c := range buf {
if unicode.IsDigit(c) {
if v, ok := arabicIndicNumberals[c]; ok {
normalizedDigits.WriteRune(v)
} else {
normalizedDigits.WriteRune(c)
}
} else if keepNonDigits {
normalizedDigits.WriteRune(c)
}
}
return normalizedDigits.String()
}
// Normalizes a string of characters representing a phone number. This
// strips all characters which are not diallable on a mobile phone
// keypad (including all non-ASCII digits).
func NormalizeDiallableCharsOnly(number string) string {
return normalizeHelper(
number, diallableCharMappings, true /* remove non matches */)
}
// Converts all alpha characters in a number to their respective digits
// on a keypad, but retains existing formatting.
func ConvertAlphaCharactersInNumber(number string) string {
return normalizeHelper(number, alphaPhoneMappings, false)
}
// 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:
//
// number, err := Parse("16502530000", "US")
// // ... deal with err appropriately ...
// nationalSignificantNumber := GetNationalSignificantNumber(number)
// var areaCode, subscriberNumber string
//
// areaCodeLength := GetLengthOfGeographicalAreaCode(number)
// if areaCodeLength > 0 {
// areaCode = nationalSignificantNumber[0:areaCodeLength]
// subscriberNumber = nationalSignificantNumber[areaCodeLength:]
// } else {
// areaCode = ""
// subscriberNumber = nationalSignificantNumber
// }
//
// 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 national_number instead. Read the following carefully before
// deciding to use this method:
//
// - geographical area codes change over time, and this method honors those changes;
// therefore, it doesn't guarantee the stability of the result it produces.
// - subscriber numbers may not be diallable from all devices (notably mobile
// devices, which typically requires the full national_number to be dialled
// in most regions).
// - most non-geographical numbers have no area codes, including numbers from
// non-geographical entities
// - some geographical numbers have no area codes.
func GetLengthOfGeographicalAreaCode(number *PhoneNumber) int {
metadata := getMetadataForRegion(GetRegionCodeForNumber(number))
if metadata == nil {
return 0
}
numType := GetNumberType(number)
countryCallingCode := number.GetCountryCode()
// 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.
// Note:this is our general assumption, but there are exceptions which are tracked in
// countriesWithoutNationalPrefixWithAreaCodes.
if len(metadata.GetNationalPrefix()) == 0 && !number.GetItalianLeadingZero() && !countriesWithoutNationalPrefixWithAreaCodes[countryCallingCode] {
return 0
}
// 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.
if numType == MOBILE && geoMobileCountriesWithoutMobileAreaCodes[countryCallingCode] {
return 0
}
if !IsNumberGeographical(number) {
return 0
}
return GetLengthOfNationalDestinationCode(number)
}
// 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. An example
// of how this could be used:
//
// number, err := Parse("18002530000", "US")
// // ... deal with err appropriately ...
// nationalSignificantNumber := GetNationalSignificantNumber(number)
// var nationalDestinationCode, subscriberNumber string
//
// nationalDestinationCodeLength := GetLengthOfNationalDestinationCode(number)
// if nationalDestinationCodeLength > 0 {
// nationalDestinationCode = nationalSignificantNumber[0:nationalDestinationCodeLength]
// subscriberNumber = nationalSignificantNumber[nationalDestinationCodeLength:]
// } else {
// nationalDestinationCode = ""
// subscriberNumber = nationalSignificantNumber
// }
//
// Refer to the unittests to see the difference between this function and
// GetLengthOfGeographicalAreaCode().
func GetLengthOfNationalDestinationCode(number *PhoneNumber) int {
var copiedProto *PhoneNumber
if len(number.GetExtension()) > 0 {
// 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 = &PhoneNumber{}
proto.Merge(copiedProto, number)
copiedProto.Extension = nil
} else {
copiedProto = number
}
nationalSignificantNumber := Format(copiedProto, INTERNATIONAL)
numberGroups := nonDigitsPattern.Split(nationalSignificantNumber, -1)
// 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 len(numberGroups) <= 3 {
return 0
}
if GetNumberType(number) == 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.
mobileToken := GetCountryMobileToken(int(number.GetCountryCode()))
if mobileToken != "" {
return len(numberGroups[2]) + len(numberGroups[3])
}
}
return len(numberGroups[2])
}
// 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.
func GetCountryMobileToken(countryCallingCode int) string {
if val, ok := mobileTokenMappings[countryCallingCode]; ok {
return val
}
return ""
}
// 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.
func normalizeHelper(number string,
normalizationReplacements map[rune]rune,
removeNonMatches bool) string {
var normalizedNumber = stringbuilder.New(nil)
for _, character := range number {
newDigit, ok := normalizationReplacements[unicode.ToUpper(character)]
if ok {
normalizedNumber.WriteRune(newDigit)
} else if !removeNonMatches {
normalizedNumber.WriteRune(character)
}
// If neither of the above are true, we remove this character.
}
return normalizedNumber.String()
}
// GetSupportedRegions returns all regions the library has metadata for.
func GetSupportedRegions() map[string]bool {
return metadata.SupportedRegions()
}
// GetSupportedCallingCodes 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.
func GetSupportedCallingCodes() map[int]bool {
return metadata.SupportedCallingCodes()
}
// GetSupportedGlobalNetworkCallingCodes returns all global network calling codes the library has metadata for.
func GetSupportedGlobalNetworkCallingCodes() map[int]bool {
return metadata.CountryCodesForNonGeographicalRegion()
}
// allPhoneNumberTypes lists every PhoneNumberType, used to iterate types like
// Java's PhoneNumberType.values().
var allPhoneNumberTypes = []PhoneNumberType{
FIXED_LINE, MOBILE, FIXED_LINE_OR_MOBILE, TOLL_FREE, PREMIUM_RATE,
SHARED_COST, VOIP, PERSONAL_NUMBER, PAGER, UAN, VOICEMAIL, UNKNOWN,
}
// descHasData returns true if there is any data set for a particular
// PhoneNumberDesc. An absent descriptor is marked with possibleLength [-1]
// (matching upstream).
func descHasData(desc *PhoneNumberDesc) bool {
if desc == nil {
return false
}
// Checking most properties since we don't know what's present, since a custom
// build may have some of them removed.
return len(desc.GetExampleNumber()) > 0 ||
descHasPossibleNumberData(desc) ||
desc.NationalNumberPattern != nil
}
// getSupportedTypesForMetadata returns the types we have metadata for based on
// the given PhoneMetadata, excluding FIXED_LINE_OR_MOBILE and UNKNOWN.
func getSupportedTypesForMetadata(metadata *PhoneMetadata) map[PhoneNumberType]bool {
types := make(map[PhoneNumberType]bool)
for _, typ := range allPhoneNumberTypes {
// Never return FIXED_LINE_OR_MOBILE (a convenience type) or UNKNOWN.
if typ == FIXED_LINE_OR_MOBILE || typ == UNKNOWN {
continue
}
if descHasData(getNumberDescByType(metadata, typ)) {
types[typ] = true
}
}
return types
}
// GetSupportedTypesForRegion returns the types for a given region which the
// library has metadata for. Will not include FIXED_LINE_OR_MOBILE or UNKNOWN.
// No types are returned for invalid or unknown region codes.
func GetSupportedTypesForRegion(regionCode string) map[PhoneNumberType]bool {
if !isValidRegionCode(regionCode) {
return map[PhoneNumberType]bool{}
}
return getSupportedTypesForMetadata(getMetadataForRegion(regionCode))
}
// GetSupportedTypesForNonGeoEntity 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 or UNKNOWN. No types are returned for
// country calling codes that do not map to a known non-geographical entity.
func GetSupportedTypesForNonGeoEntity(countryCallingCode int) map[PhoneNumberType]bool {
metadata := getMetadataForNonGeographicalRegion(countryCallingCode)
if metadata == nil {
return map[PhoneNumberType]bool{}
}
return getSupportedTypesForMetadata(metadata)
}
// Helper function to check if the national prefix formatting rule has the
// first group only, i.e., does not start with the national prefix.
func formattingRuleHasFirstGroupOnly(nationalPrefixFormattingRule string) bool {
return len(nationalPrefixFormattingRule) == 0 ||
firstGroupOnlyPrefixPattern.MatchString(nationalPrefixFormattingRule)
}
// Tests whether a phone number has a geographical association. It checks
// if the number is associated to a certain region in the country where it
// belongs to. Note that this doesn't verify if the number is actually in use.
//
// A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded,
// which performs a looser check, since it only prevents cases where prefixes
// overlap for geocodable and non-geocodable numbers. Also, if new phone
// number types were added, we should check if this other method should be
// updated too.
func IsNumberGeographical(phoneNumber *PhoneNumber) bool {
return IsNumberGeographicalForType(GetNumberType(phoneNumber), int(phoneNumber.GetCountryCode()))
}
// 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.
func IsNumberGeographicalForType(phoneNumberType PhoneNumberType, countryCallingCode int) bool {
return phoneNumberType == FIXED_LINE ||
phoneNumberType == FIXED_LINE_OR_MOBILE ||
(geoMobileCountries[int32(countryCallingCode)] && phoneNumberType == MOBILE)
}
// Helper function to check region code is not unknown or null.
func isValidRegionCode(regionCode string) bool {
valid := metadata.SupportedRegions()[regionCode]
return len(regionCode) != 0 && valid
}
// Helper function to check the country calling code is valid.
func hasValidCountryCallingCode(countryCallingCode int) bool {
_, containsKey := metadata.CountryCodeToRegion()[countryCallingCode]
return containsKey
}
// Formats a phone number in the specified format using default rules. Note
// that this does not promise to produce a phone number that the user can
// dial from where they are - although we do format in either 'national' or
// 'international' format depending on what the client asks for, we do not
// currently support a more abbreviated format, such as for users in the
// same "area" who could potentially dial the number without area code.
// Note that if the phone number has a country calling code of 0 or an
// otherwise invalid country calling code, we cannot work out which
// formatting rules to apply so we return the national significant number
// with no formatting applied.
func Format(number *PhoneNumber, numberFormat PhoneNumberFormat) string {
if number.GetNationalNumber() == 0 && len(number.GetRawInput()) > 0 {
// Unparseable numbers that kept their raw input just use that.
// This is the only case where a number can be formatted as E164
// without a leading '+' symbol (but the original number wasn't
// parseable anyway).
// TODO: Consider removing the 'if' above so that unparseable
// strings without raw input format to the empty string instead of "+00"
rawInput := number.GetRawInput()
if len(rawInput) > 0 {
return rawInput
}
}
var formattedNumber = stringbuilder.New(nil)
formatWithBuf(number, numberFormat, formattedNumber)
return formattedNumber.String()
}
// formatWithBuf formats number into the supplied buffer. It mirrors upstream's
// format(PhoneNumber, PhoneNumberFormat, StringBuilder) overload and backs the
// public Format. It is unexported because the buffer type is internal and the
// allocation reuse it would offer is negligible anyway: formatting must prepend
// the country calling code, which rebuilds the buffer on every call.
func formatWithBuf(number *PhoneNumber, numberFormat PhoneNumberFormat, formattedNumber *stringbuilder.Builder) {
// Clear the StringBuilder first.
formattedNumber.Reset()
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if numberFormat == E164 {
// Early exit for E164 case (even if the country calling code
// is invalid) since no formatting of the national number needs
// to be applied. Extensions are not formatted.
formattedNumber.WriteString(nationalSignificantNumber)
prefixNumberWithCountryCallingCode(countryCallingCode, E164, formattedNumber)
return
} else if !hasValidCountryCallingCode(countryCallingCode) {
formattedNumber.WriteString(nationalSignificantNumber)
return
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For
// example, for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is
// valid (which means that the region code cannot be ZZ and must
// be one of our supported region codes).
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber.WriteString(formatNsn(nationalSignificantNumber, metadata, numberFormat))
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber)
}
// FormatByPattern formats a phone number in the specified format using client-defined
// formatting rules. Note that if the phone number has a country calling
// code of zero or an otherwise invalid country calling code, we cannot
// work out things like whether there should be a national prefix applied,
// or how to format extensions, so we return the national significant
// number with no formatting applied.
func FormatByPattern(number *PhoneNumber,
numberFormat PhoneNumberFormat,
userDefinedFormats []*NumberFormat) string {
countryCallingCode := int(number.GetCountryCode())
nationalSignificantNumber := GetNationalSignificantNumber(number)
if !hasValidCountryCallingCode(countryCallingCode) {
return nationalSignificantNumber
}
// Note GetRegionCodeForCountryCode() is used because formatting
// information for regions which share a country calling code is
// contained by only one region for performance reasons. For example,
// for NANPA regions it will be contained in the metadata for US.
regionCode := GetRegionCodeForCountryCode(countryCallingCode)
// Metadata cannot be null because the country calling code is valid
metadata := getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)
formattedNumber := stringbuilder.New(nil)
formattingPattern := chooseFormattingPatternForNumber(
userDefinedFormats, nationalSignificantNumber)
if formattingPattern == nil {
// If no pattern above is matched, we format the number as a whole.
formattedNumber.WriteString(nationalSignificantNumber)
} else {
numFormatCopy := &NumberFormat{}
// Before we do a replacement of the national prefix pattern
// $NP with the national prefix, we need to copy the rule so
// that subsequent replacements for different numbers have the
// appropriate national prefix.
proto.Merge(numFormatCopy, formattingPattern)
nationalPrefixFormattingRule := formattingPattern.GetNationalPrefixFormattingRule()
if len(nationalPrefixFormattingRule) > 0 {
nationalPrefix := metadata.GetNationalPrefix()
if len(nationalPrefix) > 0 {
// Replace $NP with national prefix and $FG with the
// first group ($1). Java does rule.replace(FG_STRING, "$1"),
// inserting the literal characters "$1" so the first group is
// substituted later by formatNsnUsingPattern. Use a literal
// replacement here because Go's ReplaceAllString would treat
// "$1" as a group reference into fgPattern (which has no
// groups), leaving a stray backslash instead.
nationalPrefixFormattingRule =
npPattern.ReplaceAllString(
nationalPrefixFormattingRule, nationalPrefix)
nationalPrefixFormattingRule =
fgPattern.ReplaceAllLiteralString(
nationalPrefixFormattingRule, "$1")
numFormatCopy.NationalPrefixFormattingRule =
&nationalPrefixFormattingRule
} else {
// We don't want to have a rule for how to format the
// national prefix if there isn't one.
numFormatCopy.NationalPrefixFormattingRule = nil
}
}
formattedNumber.WriteString(
formatNsnUsingPattern(
nationalSignificantNumber, numFormatCopy, numberFormat))
}
maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber)
prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber)
return formattedNumber.String()
}
// Formats a phone number in national format for dialing using the carrier
// as specified in the carrierCode. The carrierCode will always be used
// regardless of whether the phone number already has a preferred domestic
// carrier code stored. If carrierCode contains an empty string, returns
// the number in national format without any carrier code.