US ZIP Code in GO
Match US ZIP codes in 5-digit (12345) and ZIP+4 (12345-6789) formats.
Try it in the GO tester →Pattern
regexGO
\b\d{5}(?:[\-\s]\d{4})?\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b\d{5}(?:[\-\s]\d{4})?\b`)
input := `90210`
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
Core is 5 digits. The optional group (?:[\-\s]\d{4})? adds support for the ZIP+4 extension separated by hyphen or space.
Examples
Input
90210Matches
90210
Input
10001-1234Matches
10001-1234
Input
1234No match
—