Pattern Breakdown
Understanding the regex pattern ^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$:
- ^ - Start of string
- $ - End of string
- \d - Any digit (0-9)
- ? - Optional (zero or one)
- [...] - Character class
Examples
| Input | Result | Explanation |
|---|---|---|
K1A 0B1 |
✓ Match | Ottawa postal code |
M5V3L9 |
✓ Match | Toronto without space |
Code Examples
JavaScript
JavaScript
const pattern = /^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$/;
const text = "K1A 0B1";
// Test if string matches
if (pattern.test(text)) {
console.log("Valid!");
}
// Extract matches
const matches = text.match(pattern);
console.log(matches);
Python
Python
import re
pattern = r'^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$'
text = "K1A 0B1"
# Test if string matches
if re.match(pattern, text):
print("Valid!")
# Find all matches
matches = re.findall(pattern, text)
print(matches)
PHP
PHP
<?php
$pattern = '/^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$/';
$text = "K1A 0B1";
// Test if string matches
if (preg_match($pattern, $text)) {
echo "Valid!";
}
// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>
Java
Java
import java.util.regex.*;
String pattern = "^[A-Za-z]\\d[A-Za-z] ?\\d[A-Za-z]\\d$";
String text = "K1A 0B1";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
if (m.matches()) {
System.out.println("Valid!");
}
Use Cases
Common applications: Canadian address forms, Canada Post
- Form validation and input sanitization
- Data extraction and parsing
- Search and replace operations
- API request/response validation
- Log file analysis
Frequently Asked Questions
What is the regex pattern for canadian postal code regex?
The regex pattern is: ^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$. Validate Canadian postal codes in A1A 1A1 format.
How do I use the canadian postal code regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^[A-Za-z]\\d[A-Za-z] ?\\d[A-Za-z]\\d$'); or const regex = /^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for canadian postal code regex?
Canadian address forms, Canada Post
Related Regex Patterns
More Regex Tools
GetDevUtils offers a suite of developer tools including:
- Regex Tester - Test and debug regular expressions
- JSON Formatter - Format and validate JSON
- Base64 Encoder/Decoder - Encode and decode Base64
- URL Encoder/Decoder - Encode and decode URLs