UK Postcode in GO
Match UK postcodes in the common outward + inward format (e.g. SW1A 1AA, EC1V 9LB).
Try it in the GO tester →Pattern
regexGO
[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2} (flags: gi)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?i)[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}`)
input := `SW1A 1AA`
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
1–2 letters, 1 digit, optional letter/digit, optional space, 1 digit, 2 letters. Case-insensitive flag handles lower and mixed case input.
Examples
Input
SW1A 1AAMatches
SW1A 1AA
Input
EC1V 9LBMatches
EC1V 9LB
Input
B33 8THMatches
B33 8TH