Skip to content

Instantly share code, notes, and snippets.

@geoffgarside
Created December 1, 2010 12:19
Show Gist options
  • Save geoffgarside/723410 to your computer and use it in GitHub Desktop.
Save geoffgarside/723410 to your computer and use it in GitHub Desktop.
Construction of a UK Postcode Regular Expression

First Half

Character sets for positions

  1. [A-PR-UWYZ]
  2. [A-HK-Y]
  3. [A-HJKS-UW]
  4. [ABEHMNPRV-Y]

Formats

  1. AN [A-PR-UWYZ][0-9]
  2. ANN [A-PR-UWYZ][0-9]{2}
  3. AAN [A-PR-UWYZ][A-HK-Y][0-9]
  4. AANN [A-PR-UWYZ][A-HK-Y][0-9]{2}
  5. ANA [A-PR-UWYZ][0-9][A-HJKS-UW]
  6. AANA [A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]

Reordered Formats

  1. AN [A-PR-UWYZ][0-9]
  2. ANN [A-PR-UWYZ][0-9][0-9]
  3. ANA [A-PR-UWYZ][0-9][A-HJKS-UW]
  4. AAN [A-PR-UWYZ][A-HK-Y][0-9]
  5. AANN [A-PR-UWYZ][A-HK-Y][0-9][0-9]
  6. AANA [A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]

Combined Formats

1,2,3.

[A-PR-UWYZ][0-9]([0-9]|[A-HJKS-UW])?

4,5,6.

[A-PR-UWYZ][A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?

Combined

[A-PR-UWYZ]([0-9]([0-9]|[A-HJKS-UW])?|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?)

Second Half

  1. [0-9]
  2. [ABD-HJLNP-UW-Z]
  3. [ABD-HJLNP-UW-Z]

Combined

\s[0-9][ABD-HJLNP-UW-Z]{2}

First and Second Combined

[A-PR-UWYZ]([0-9]([0-9]|[A-HJKS-UW])?|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?)\s[0-9][ABD-HJLNP-UW-Z]{2}

Historical Exceptions

  1. GIR 0AA

Full Combined

(GIR 0AA|[A-PR-UWYZ](?:[0-9](?:[0-9]|[A-HJKS-UW])?|[A-HK-Y][0-9](?:[0-9]|[ABEHMNPRV-Y])?)\s[0-9][ABD-HJLNP-UW-Z]{2})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment