REGEXVAULTv2.0
Localization/Postal Codes
Verified Safe

UK Postcode (Full Format) Regex for Java

/^(?:GIR\s*0AA$|[A-PR-UWYZ](?:[A-HK-Y][0-9][0-9A-HJKMNPR-VWY]?|[0-9][0-9A-HJKMNPR-VWY]?)\s[0-9][ABD-HJLNP-UW-Z]{2})$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching uk postcode (full format), ported and verified for Java. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// UK Postcode (Full Format)
// ReDoS-safe | RegexVault — Localization > Postal Codes

import java.util.regex.Pattern;

public class UkPostcodeFullFormatValidator {
    private static final Pattern PATTERN =
        Pattern.compile("^(?:GIR\\s*0AA$|[A-PR-UWYZ](?:[A-HK-Y][0-9][0-9A-HJKMNPR-VWY]?|[0-9][0-9A-HJKMNPR-VWY]?)\\s[0-9][ABD-HJLNP-UW-Z]{2})$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("SW1A 1AA")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
SW1A 1AASW1A1AA
EC1A 1BBSW1A 1A
W1A 0AXZZ1 1AA
M1 1AESW1A 1AI
CR2 6XHSW1A 1AO
DN55 1PTSW1A 1AV
GIR 0AA

When to use this pattern

This pattern is drawn from the Localization > Postal Codes category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

UK postcodes require a space between outward and inward codes for canonical format. Many systems strip the space for storage — normalize before comparison. BFPO postcodes follow a different format.

Technical Notes

Structure: area (1-2 letters) + district (1-2 alphanumeric) + space + sector (1 digit) + unit (2 letters). The inward code letters exclude C, I, K, M, O, V. GIR 0AA is the only postcode without a space.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern