Skip to content

Instantly share code, notes, and snippets.

@TimTaylor
Created March 5, 2020 13:02
Show Gist options
  • Save TimTaylor/b2e51a3c260046e499a58f8762af1c8e to your computer and use it in GitHub Desktop.
Save TimTaylor/b2e51a3c260046e499a58f8762af1c8e to your computer and use it in GitHub Desktop.
R postcode validation
# Can't remember why I have two of these (found while cleaning up my files so put here)
valid_postcode_1 <- function(x) {
# remove whitespace
x <- gsub("\\s", "", x)
# convert to upper case
x <- toupper(x)
# regex (this allows for cas)
pattern <- "^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$"
# return indices of postcodes that match pattern
grep(pattern, x, perl = TRUE)
}
valid_postcode_2 <- function(x) {
# remove whitespace
x <- gsub("\\s", "", x)
# convert to upper case
x <- toupper(x)
# regex (this allows for cas)
pattern <- ^(([A-Z][0-9]{1,2})|(([A-Z][A-HJ-Y][0-9]{1,2})|(([A-Z][0-9][A-Z])|([A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2}$
# return indices of postcodes that match pattern
grep(pattern, x, perl = TRUE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment