How to correctly match UK postcodes by prefix?

前端 未结 6 1519
说谎
说谎 2020-12-19 23:08

I have a number of restaurants who all deliver to certain postcode areas in London, for example:

  • EC1
  • WC1
  • WC2<
6条回答
  •  误落风尘
    2020-12-19 23:41

    I use the following regex which matches the prefix part only but uses a lookahead to make sure the full postcode is valid (including an optional space)

    (GIR|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]))(?=( )?[0-9][ABD-HJLNP-UW-Z]{2})
    

    It's not quite perfect as it will match some postcodes that aren't valid (eg starting AA, etc) but if you're using it to look up the prefix anyway it should do the trick.

    ps. I just noted that the regex supplied by the UK Government has been updated since I first implemented this. I which case this can be updated to:

    (GIR|([A-Z-[QVX][0-9][0-9]?)|(([A-Z-[QVX][A-Z-[IJZ][0-9][0-9]?)|(([A-Z-[QVX][0-9][A-HJKSTUW])|([A-Z-[QVX][A-Z-[IJZ][0-9][ABEHMNPRVWXY]))))(?=( )?[0-9][A-Z-[CIKMOV]{2})
    

提交回复
热议问题