Skip to content

Commit

Permalink
fix FormatByPattern with user defined pattern. Fixes: #16
Browse files Browse the repository at this point in the history
  • Loading branch information
nicpottier committed Oct 19, 2018
1 parent 3c4b91a commit 5faf6ce
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
4 changes: 2 additions & 2 deletions phonenumbers.go
Original file line number Diff line number Diff line change
Expand Up @@ -1109,7 +1109,7 @@ func FormatWithBuf(number *PhoneNumber, numberFormat PhoneNumberFormat, formatte
prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber)
}

// Formats a phone number in the specified format using client-defined
// 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,
Expand Down Expand Up @@ -1140,7 +1140,7 @@ func FormatByPattern(number *PhoneNumber,
// If no pattern above is matched, we format the number as a whole.
formattedNumber.WriteString(nationalSignificantNumber)
} else {
var numFormatCopy *NumberFormat
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
Expand Down
49 changes: 49 additions & 0 deletions phonenumbers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,51 @@ func TestFormatForMobileDialing(t *testing.T) {
}
}

func TestFormatByPattern(t *testing.T) {
var tcs = []struct {
in string
region string
format PhoneNumberFormat
userFormats []*NumberFormat
exp string
}{
{
in: "+33122334455",
region: "FR",
format: E164,
userFormats: []*NumberFormat{
&NumberFormat{
Pattern: s(`(\d+)`),
Format: s(`$1`),
},
},
exp: "+33122334455",
}, {
in: "+442070313000",
region: "UK",
format: NATIONAL,
userFormats: []*NumberFormat{
&NumberFormat{
Pattern: s(`(20)(\d{4})(\d{4})`),
Format: s(`$1 $2 $3`),
},
},
exp: "20 7031 3000",
},
}

for i, tc := range tcs {
num, err := Parse(tc.in, tc.region)
if err != nil {
t.Errorf("[test %d] failed: should be able to parse, err:%v\n", i, err)
}
got := FormatByPattern(num, tc.format, tc.userFormats)
if got != tc.exp {
t.Errorf("[test %d:fmt] failed %s != %s\n", i, got, tc.exp)
}
}
}

func TestSetItalianLeadinZerosForPhoneNumber(t *testing.T) {
var tests = []struct {
num string
Expand Down Expand Up @@ -1275,3 +1320,7 @@ func TestRegexCacheStrict(t *testing.T) {
t.Errorf("phone number formatting not as expected")
}
}

func s(str string) *string {
return &str
}

0 comments on commit 5faf6ce

Please sign in to comment.