Canadian Postal Code in GO
Match Canadian postal codes in the A1A 1A1 or A1A1A1 format with valid first-letter prefixes.
Try it in the GO tester →Pattern
regexGO
[ABCEGHJ-NPRSTVXY]\d[A-Z] ?\d[A-Z]\d (flags: gi)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?i)[ABCEGHJ-NPRSTVXY]\d[A-Z] ?\d[A-Z]\d`)
input := `K1A 0B1`
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
The leading character is constrained to letters actually used by Canada Post (D, F, I, O, Q, U, W, Z are excluded). Alternating letter-digit pattern, with an optional space separator.
Examples
Input
K1A 0B1Matches
K1A 0B1
Input
M5V3L9Matches
M5V3L9
Input
12345No match
—