RegExLib.com - The first Regular Expression Library on the Web!

Please support RegExLib Sponsors

Sponsors

Regular Expression Details

Title Test Find UK Postcodes (tight and validated)
Expression
(?<O>(?<d>[BEGLMNS]|A[BL]|B[ABDHLNRST]|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]|F[KY]|G[LUY]|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]|M[EKL]|N[EGNPRW]|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKL-PRSTWY]|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)(?<a>\d\d?)|(?<d>E)(?<a>\dW)|(?<d>EC)(?<a>\d[AMNPRVY0])|(?<d>N)(?<a>\dP)|(?<d>NW)(?<a>\dW)|(?<d>SE)(?<a>\dP)|(?<d>SW)(?<a>\d[AEHPVWXY])|(?<d>W)(?<a>1[0-4A-DFGHJKSTUW])|(?<d>W)(?<a>[2-9])|(?<d>WC)(?<a>[12][ABEHNRVX]))\ (?<I>(?<s>\d)(?<u>[ABD-HJLNP-UW-Z]{2}))
Description
This is the tightest uk postcode validator I can come up with, I have copy of Royal Mail's PAF (Postal Address File) and I've confirmed that it will correctly validate all 1.75 million distinct postcodes. I figure this regex will accept 54 million strings as valid, which gives a 30:1 false accept ratio, the best I can do. I'll endeavour to keep it up to date with new post codes. I've deliberately excluded special cases, These can be added as simple alternates. 2009-06-05 Improved: Replaced all numbered captured groups with 6 named capture groups (I Incode, O Outcode, d District, s Sector, a Area, u Unit) for separating postcode parts. Also removed begin (^) and end ($) positioning characters ST
Matches
CR0 1AA|EC50 1AA|SW1P 1AA|GU1 3AW
Non-Matches
DR1 1AA|EC51 1AA|sw1p 1aa|CR01AA|GIR 0AA|SAN TA1|BFPO 2|ASCN 1ZZ
Author Rating: The rating for this expression. Stephen Turner
Source Based on Howard Richards (#1047) and PAF Data
Your Rating
Bad Good

Enter New Comment

Title

Name

Comment

Spammers suck - we apologize. Please enter the text shown below to enable your comment (not case sensitive - try as many times as you need to if the first ones are too hard):

Existing User Comments

Title: N1C postcodes are flagged as invalid
Name: Dermot Murphy
Date: 7/19/2023 10:26:32 AM
Comment:
I have run this against the ONSPD_MAY_2023_UK dataset for all postcodes which have not been terminated (1,794,832 postcodes). Only 76 failures, all in Area 'N1C'. It is still an excellent regex and the grouping is appreciated. 9.5 out of 10 👍


Title: Post Code
Name: Xavier
Date: 12/1/2011 5:48:47 AM
Comment:
This result is also valid for Post Code.


Title: No space between start and end of postcode
Name: Chris Hey
Date: 10/13/2011 4:49:49 AM
Comment:
Why would you not allow a space in th middle of the postcode? For example CR01AA, when CR0 1AA is valid.


Copyright © 2001-2025, RegexAdvice.com | ASP.NET Tutorials