Search code examples
javaregexpostal-code

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?


Solution

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