Regex for UK Postcode
Regex Pattern
^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$UK postcode format
Quick Answer
The regex pattern for uk postcode is `^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$`. UK postcode format. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| SW1A 1AA | ✓ Matches |
| M1 1AA | ✓ Matches |
| B33 8TH | ✓ Matches |
| DN55 1PT | ✓ Matches |
| 12345 | ✗ No match |
| SW1A | ✗ No match |
| lowercase sw1a 1aa | ✗ No match |
Code Examples
javascript
const regex = /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/;
const isValid = regex.test(value);python
import re
pattern = r'^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$'
if re.match(pattern, value):
print("valid")ruby
pattern = /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/
if value =~ pattern
puts "valid"
endphp
if (preg_match('/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/', $value)) {
echo "valid";
}java
String pattern = "^[A-Z]{1,2}\\d[A-Z\\d]? ?\\d[A-Z]{2}$";
boolean isValid = value.matches(pattern);Frequently Asked Questions
Related Regex Patterns
US ZIP Code
5-digit ZIP or ZIP+4 format
Indian PIN Code
6-digit Indian PIN code
Canadian Postal Code
Canadian postal code (letter-digit-letter digit-letter-digit)
Email Address
Validates a standard email address format
Email (RFC 5322 Compliant)
RFC 5322 compliant email validation with label length limits
URL (HTTP/HTTPS)
Validates HTTP and HTTPS URLs