RegEx for matching UK Postcodes

前端 未结 30 2448
广开言路
广开言路 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:53

    I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):

    /^([a-z0-9]\s*){5,8}$/i
    

    This allows the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET".

    Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: "OL145ETX". But again, this is a simplistic regex, for when that's good enough.

提交回复
热议问题