Skip to content

Instantly share code, notes, and snippets.

@simonwhitaker
Last active December 15, 2023 11:29
Show Gist options
  • Save simonwhitaker/5748487 to your computer and use it in GitHub Desktop.
Save simonwhitaker/5748487 to your computer and use it in GitHub Desktop.
An example of using a simplified UK postcode regex in Javascript
var tweet = "Currently chilling out at W1B 2EL, then on to WC2E 8HA or maybe even L1 8JF! :-)";
// Here's a simple regex that tries to recognise postcode-like strings.
// See http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
// for the rules on how UK postcodes are formatted.
var postcode_regex = /[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/g;
var postcodes = tweet.match(postcode_regex);
console.log(postcodes);
@mtmgoliath
Copy link

Thanks for the helpful post!

My use case needed it to also work with 0 or 1 spaces {0,1}, so here is my slightly modded version for anyone's convenience, including future me!

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment