Canadian Postal Code Regex for Java
/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching canadian postal code, 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
// Canadian Postal Code
// ReDoS-safe | RegexVault — Localization > Postal Codes
import java.util.regex.Pattern;
public class CanadianPostalCodeValidator {
private static final Pattern PATTERN =
Pattern.compile("^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("K1A 0B1")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
K1A 0B1 | K1A 0B |
M5V 3L9 | K1A0B12 |
V6B 1G4 | Z1A 0B1 |
T2P 3C3 | K1A OB1 |
K1A0B1 | D1A 0B1 |
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
The FSA (Forward Sortation Area, first 3 characters) uniquely identifies a delivery area. The LDU (Local Delivery Unit, last 3) narrows to a block. The boundary between FSA and LDU is always a space.
Technical Notes
First letter identifies the province. Invalid first letters: D, F, I, O, Q, U, W (excluded because they resemble digits in some fonts or were reserved). The letter D and I are also excluded from all positions for readability.
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