-
Notifications
You must be signed in to change notification settings - Fork 20
/
phone.go
39 lines (31 loc) · 966 Bytes
/
phone.go
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
package utils
import (
"regexp"
"strings"
"github.com/nyaruka/gocommon/i18n"
"github.com/nyaruka/gocommon/urns"
)
var possiblePhone = regexp.MustCompile(`\+?[\d \.\-\(\)]{5,}`)
var onlyPhone = regexp.MustCompile(`^` + possiblePhone.String() + `$`)
// ParsePhoneNumber tries to parse the given string as a phone number. If successful, it returns it formatted as E164.
func ParsePhoneNumber(s string, country i18n.Country) string {
s = strings.TrimSpace(s)
if !onlyPhone.MatchString(s) {
return ""
}
formatted, err := urns.ParseNumber(s, country, false, false)
if err != nil {
return ""
}
return formatted
}
// FindPhoneNumbers finds phone numbers anywhere in the given string
func FindPhoneNumbers(s string, country i18n.Country) []string {
nums := make([]string, 0)
for _, candidate := range possiblePhone.FindAllString(s, -1) {
if num := ParsePhoneNumber(candidate, country); num != "" {
nums = append(nums, num)
}
}
return nums
}