I need a regex to match the first half of a uk postcode, and it's possible just one half or a full post code could get passed in.
There is great way to match full postcode here: UK Postcode Regex (Comprehensive)
However I need to just get the first 3 or 4 characters of a postcode, with the possibility of half a post code or a postcode without spaces getting passed in, so any of these:
SL4 4BZ
SL44BZ - this will pull out just 'SL4'
SL4
DY10
DY10 3BD
DY10 3BD
The regex needs to match:
- if it's 5 characters long (excluding spaces), remove last 3 characters and the first 2 remaining characters are the half-a-postcode
- if it's 6 characters long (excluding spaces), remove last 3 characters and the first 3 remaining characters are the half-a-postcode
- if it's 7 characters long (excluding spaces), remove last 3 characters and the first 4 remaining characters are the half-a-postcode
- if it's 2, 3 or 4 characters long, keep it
But I can't quite get my head around how to write something this complex.