RegEx for matching UK Postcodes

前端 未结 30 2475
广开言路
广开言路 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 01:55

    here's how we have been dealing with the UK postcode issue:

    ^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$
    

    Explanation:

    • expect 1 or 2 a-z chars, upper or lower fine
    • expect 1 or 2 numbers
    • expect 0 or 1 a-z char, upper or lower fine
    • optional space allowed
    • expect 1 number
    • expect 2 a-z, upper or lower fine

    This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint https://www.ordnancesurvey.co.uk/opendatadownload/products.html

    hope this helps

提交回复
热议问题