0

I need a regex that will match UK postcodes, including partial and full postcodes.

I've already tried various stack overflow suggestions from previous threads

previous attempt

var partialPostCode = /^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$/; 

Expected

partialPostCode.test('jt14 8eb') => true (previous regex true)

partialPostCode.test('jt14 8e')=> true (previous regex false)

partialPostCode.test('jt14') => true (previous regex true)
logi-kal
  • 7,107
  • 6
  • 31
  • 43
  • It will match if you change the last `{2}` to `{0,2}` ([demo](https://regex101.com/r/9dlnWC/1)). What are you doing, BTW? Live input validation? – Wiktor Stribiżew Jun 07 '19 at 10:01
  • 2
    Possible duplicate of [Pattern match a partial British postcode](https://stackoverflow.com/questions/23930574/pattern-match-a-partial-british-postcode) – Liam Jun 07 '19 at 10:19
  • @Liam The regex OP uses is from that thread. – Wiktor Stribiżew Jun 07 '19 at 10:23
  • Note that since none of the letters in your pattern are case-sensitive, you can simplify to `/^((GIR *0AA)|((([A-PR-UWYZ][A-HK-Y]?\d\d?)|(([A-PR-UWYZ]\d[A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y]\d[ABEHMNPRV-Y])))( *\d[ABD-HJLNP-UW-Z]{2})?))$/i`. You probably also don’t need to capture that much (the parentheses). – Ry- Jun 07 '19 at 10:23

0 Answers0