Search code examples
phpregexperlpostal-code

Regex to specific rule


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.


Solution

  • 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.