Regular Expressions 101

Community Patterns

1...34567...901

Community Library Entry

22

Regular Expression
PCRE (PHP <7.3)

/
^([a-zA-Z]{1,2}\d{1,2})\s*?(\d[a-zA-Z]{2})$
/
gmi

Description

Checks for valid UK/British postcodes.

There was another on here that had for some reason been upvoted, but it was actually incorrect as it worked on none of my valid own postcodes! Namely that it assumed two letters and a number (BS3) when you can have variations (M20). Allows for an optional space and separates the two parts into groups.

Submitted by MaffooBristol - 10 years ago