International Phone Number (Loose) in GO
Match international phone numbers in a variety of loose formats including country codes, area codes, and separators.
Try it in the GO tester →Pattern
regexGO
\+?[1-9]\d{0,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,4}\d{1,9} (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\+?[1-9]\d{0,3}[\s.\-]?(?:\(?\d{1,4}\)?[\s.\-]?){2,4}\d{1,9}`)
input := `+1 (415) 555-2671`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
\+? optionally matches a leading +. [1-9]\d{0,3} matches 1–4 digit country/area code. The repeating group (?:\(?\d{1,4}\)?[\s.\-]?){2,4} matches digit groups with optional parentheses and separators. Ends with 1–9 final digits.
Examples
Input
+1 (415) 555-2671Matches
+1 (415) 555-2671
Input
+44 20 7183 8750Matches
+44 20 7183 8750
Input
not a phoneNo match
—