Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split UK postcode into two main parts using java

This regular expression for validating postcodes works perfect

^([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})$

but I want to split the postcodes to retrieve the individual parts of the postcode using java.

How can this be done in java?

like image 817
Farouk Alhassan Avatar asked May 30 '26 22:05

Farouk Alhassan


2 Answers

Here are the official regexes for matching UK postcodes:

http://interim.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm

If you want to split a found postcode into it's two parts, isn't it simply a question of splitting on whitespace? A UK postcode's two parts are just separated by a space, right? In java this would be:

String[] fields = postcode.split("\\s");

where postcode is a validated postcode and fields[] will be an array of length 2 containing the first and second parts.

Edit: If this is to validate user input, and you want to validate the first part, your regex would be:

Pattern firstPart = Pattern.compile("[A-Z]{1,2}[0-9R][0-9A-Z]?");

To validate the second part it is:

Pattern secondPart = Pattern.compile("[0-9][A-Z-[CIKMOV]]{2}");
like image 111
Richard H Avatar answered Jun 01 '26 12:06

Richard H


I realise that it's rather a long time since this question was asked, but I had the same requirement and thought that I'd post my solution in case it helps someone out there :

const string matchString = @"^(?<Primary>([A-Z]{1,2}[0-9]{1,2}[A-Z]?))(?<Secondary>([0-9]{1}[A-Z]{2}))$";

var regEx = new Regex(matchString);
var match = regEx.Match(Postcode);

var postcodePrimary = match.Groups["Primary"];
var postcodeSecondary = match.Groups["Secondary"];

This doesn't validate the postcode, but it does split it into 2 parts if no space has been entered between them.

like image 23
Gareth Avatar answered Jun 01 '26 12:06

Gareth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!