Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active November 13, 2023 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croxton/d21352ae17b01e3355a96f376d05940c to your computer and use it in GitHub Desktop.
Save croxton/d21352ae17b01e3355a96f376d05940c to your computer and use it in GitHub Desktop.
Regex to match UK mainland postcodes (i.e. excluding UK Highlands and Islands postcodes)
Exclude UK Highland and Islands Regex:
^ # Start of line
(?! # Exclude the following
IV([1-9]|[1-4][0-9]|5[0-6])[\s]*([\d][A-Za-z]{2}) # Inverness IV1 - IV56
| # or
BT[0-9]{1,2}[\s]*([\d][A-Za-z]{2}) # Belfast BT
|
GY[0-9]{1,2}[\s]*([\d][A-Za-z]{2}) # Guernsey GY
|
HS[1-9][\s]*([\d][A-Za-z]{2}) # Outer Hebrides HS1 - HS9
|
IM[0-9]{1,2}[\s]*([\d][A-Za-z]{2}) # Isle of Man IM
|
JE[0-9]{1,2}[\s]*([\d][A-Za-z]{2}) # Jersey JE
|
KA(27|28)[\s]*([\d][A-Za-z]{2}) # Kilmarnock KA27 - KA28
|
KW([1-4]|1[5-7])[\s]*([\d][A-Za-z]{2}) # Kirkwall KW1 - KW4 & KW15 - KW17
|
PA(20|34|(3[7-9])|4[1-8]|(6[0-9]|7[0-8]))[\s]*([\d][A-Za-z]{2}) # Paisley PA20, PA34, PA37 - PA39, PA41 - PA48 and PA60 - PA78
|
PH((19|2[0-6])|(3[0-9]|4[0-4])|49|50)[\s]*([\d][A-Za-z]{2}) # Perth PH19 - PH26, PH30 - PH44, PH49, PH50
|
PO(3[0-9]|4[01])[\s]*([\d][A-Za-z]{2}) # Isle of White PO30 - PO41
|
TR2[1-5][\s]*([\d][A-Za-z]{2}) # Scily Isles TR21 - TR25
|
ZE[1-3][\s]*([\d][A-Za-z]{2}) # Lerwick ZE1 - ZE3
)
[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2} # Match all other valid UK postcodes
$ # End of line
Compact:
^(?!IV([1-9]|[1-4][0-9]|5[0-6])[\s]*([\d][A-Za-z]{2})|BT[0-9]{1,2}[\s]*([\d][A-Za-z]{2})|GY[0-9]{1,2}[\s]*([\d][A-Za-z]{2})|HS[1-9][\s]*([\d][A-Za-z]{2})|IM[0-9]{1,2}[\s]*([\d][A-Za-z]{2})|JE[0-9]{1,2}[\s]*([\d][A-Za-z]{2})|KA(27|28)[\s]*([\d][A-Za-z]{2})|KW([1-4]|1[5-7])[\s]*([\d][A-Za-z]{2})|PA(20|34|(3[7-9])|4[1-8]|(6[0-9]|7[0-8]))[\s]*([\d][A-Za-z]{2})|PH((19|2[0-6])|(3[0-9]|4[0-4])|49|50)[\s]*([\d][A-Za-z]{2})|PO(3[0-9]|4[01])[\s]*([\d][A-Za-z]{2})|TR2[1-5][\s]*([\d][A-Za-z]{2})|ZE[1-3][\s]*([\d][A-Za-z]{2}))[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment