0

I need to recreate this logic using regex.

if $postcode.length > 0 and $postcode.length < 10 AND $postcode's first character is a letter and (second or third character is a number) then it's a match.

I came up with this following regex:

/((^[a-z]+[0-9]?[0-9]){1,9}$)/i

It needs to match these examples:

  • B1 8PT
  • SW12 TQ1
  • B12 TYP
  • A1AAAAAAA
  • AA1AAAAAA

Edited: My current regex doesn't match any of the examples on the list. I can't figure why. Any help would be appreciated.

Mokky Miah
  • 1,213
  • 2
  • 11
  • 29

2 Answers2

5

Here's a pattern:

^[A-Z](?=.?\d)[A-Z0-9 ]{0,8}$

Demo.

I used the lookahead (?=.?\d) to check the second or third character to see if it's a digit.

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1

With an alternation:

/^[a-z](?:[0-9].{0,7}|.[0-9].{0,6})$/i
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125