RegEx for matching UK Postcodes

前端 未结 30 2441
广开言路
广开言路 2020-11-22 01:38

I\'m after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For in

相关标签:
30条回答
  • 2020-11-22 02:05

    Basic rules:

    ^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$
    

    Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. The regular expression just shown therefore sticks to the basic rules.

    Complete rules:

    If you need a regex that ticks all the boxes for the postcode rules at the expense of readability, here you go:

    ^(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$
    

    Source: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s16.html

    Tested against our customers database and seems perfectly accurate.

    0 讨论(0)
  • 2020-11-22 02:05

    Below method will check the post code and provide complete info

    const valid_postcode = postcode => {
        try {
            postcode = postcode.replace(/\s/g, "");
            const fromat = postcode
                .toUpperCase()
                .match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
            const finalValue = `${fromat[1]} ${fromat[2]}`;
            const regex = /^([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})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/i;
            return {
                isValid: regex.test(postcode),
                formatedPostCode: finalValue,
                error: false,
                info: 'It is a valid postcode'
            };
        } catch (error) {
            return { error: true , info: 'Invalid post code has been entered!'};
        }
    };
    
    valid_postcode('GU348RR')
    result => {isValid: true, formatedPostCode: "GU34 8RR", error: false, info: "It is a valid postcode"}
    
    valid_postcode('sdasd4746asd')
    result => {error: true, info: "Invalid post code has been entered!"}
    
    valid_postcode('787898523')
    result => {error: true, info: "Invalid post code has been entered!"}
    
    0 讨论(0)
  • 2020-11-22 02:07

    Most of the answers here didn't work for all the postcodes I have in my database. I finally found one that validates with all, using the new regex provided by the government:

    https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/413338/Bulk_Data_Transfer_-_additional_validation_valid_from_March_2015.pdf

    It isn't in any of the previous answers so I post it here in case they take the link down:

    ^([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-9][A-Za-z]{2})$
    

    UPDATE: Updated regex as pointed by Jamie Bull. Not sure if it was my error copying or it was an error in the government's regex, the link is down now...

    UPDATE: As ctwheels found, this regex works with the javascript regex flavor. See his comment for one that works with the pcre (php) flavor.

    0 讨论(0)
  • 2020-11-22 02:08

    This is the regex Google serves on their i18napis.appspot.com domain:

    GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}
    
    0 讨论(0)
  • 2020-11-22 02:11

    I use the following regex that I have tested against all valid UK postcodes. It is based on the recommended rules, but condensed as much as reasonable and does not make use of any special language specific regex rules.

    ([A-PR-UWYZ]([A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})
    

    It assumes that the postcode has been converted to uppercase and has not leading or trailing characters, but will accept an optional space between the outcode and incode.

    The special "GIR0 0AA" postcode is excluded and will not validate as it's not in the official Post Office list of postcodes and as far as I'm aware will not be used as registered address. Adding it should be trivial as a special case if required.

    0 讨论(0)
  • 2020-11-22 02:11

    To check a postcode is in a valid format as per the Royal Mail's programmer's guide:

              |----------------------------outward code------------------------------| |------inward code-----|
    #special↓       α1        α2    AAN  AANA      AANN      AN    ANN    ANA (α3)        N         AA
    ^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) [0-9][ABD-HJLNP-UW-Z]{2})$
    

    All postcodes on doogal.co.uk match, except for those no longer in use.

    Adding a ? after the space and using case-insensitive match to answer this question:

    'se50eg'.match(/^(GIR 0AA|[A-PR-UWYZ]([A-HK-Y]([0-9][A-Z]?|[1-9][0-9])|[1-9]([0-9]|[A-HJKPSTUW])?) ?[0-9][ABD-HJLNP-UW-Z]{2})$/ig);
    Array [ "se50eg" ]
    
    0 讨论(0)
提交回复
热议问题