Regular Expressions 101

Community Patterns

Postcode validation

1

Regular Expression
PCRE2 (PHP >=7.3)

/
^((\d{4} [A-Z]{2})|(\d{3,6})|(\d{5}(-\d{4})?)|([A-Z0-9]{1,4} [A-Z0-9]{1,4}))$
/

Description

I come across Dutch postcodes quite different from normal 5 or 6 digit postcodes. So, this regex covers most possible postcodes.

Test cases: 1234 AB // Dutch postal code 12345 // Generic 5-digit postal code 380059 // Indian 6-digit postal code 12345-6789 // Generic 9-digit postal code K1A 0B1 // Canadian postal code SW1A 1AA // UK postal code 8155 // Invalid for the Netherlands but could be valid elsewhere

P.S. if you find any exceptional case you can add comment and we can make it better.

Submitted by Pratik P - 20 days ago