开发者

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开发者_JS百科-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?


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}");


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.


You can use the Google's recentlly open sourced library for this. http://code.google.com/p/libphonenumber/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜