RegEx for matching UK Postcodes

前端 未结 30 2947
广开言路
广开言路 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: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" ]
    

提交回复
热议问题