Pakistan Special
Pakistan Postal Code Regex
Pakistan Post uses five-digit postal codes, such as 44000 for parts of Islamabad, 54000 for Lahore and 74000 for Karachi. This pattern accepts exactly five digits and nothing else, so codes with spaces, letters or the wrong number of digits fail. It is a simple, reliable check for the postal code field of a checkout or address form. Because the rule is only about length and digits, it cannot confirm that a code is assigned to a real post office or that it matches the city the user typed; a lookup table is needed for that kind of cross-check.
Pattern (JavaScript)
/^\d{5}$/Starts at the start of the line/string, then exactly 5 digits, then the end of the line/string.
Examples
Matches
- ✓ 44000
- ✓ 54000
- ✓ 74200
Does not match
- ✗ 4400
- ✗ 440000
- ✗ 44 000
Try it
0 matches (JavaScript engine)
44000
54000
74200
4400
440000
44 000Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^\d{5}$/g;
const text = "44000";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^\d{5}$')
text = '44000'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^\d{5}$/';
$text = '44000';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^\\d{5}$");
String text = "44000";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\d{5}$`)
text := "44000"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^\d{5}$");
var text = "44000";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^\d{5}$").unwrap();
let text = "44000";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^\d{5}$/
text = '44000'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Can I check that the postal code matches the city?
- Not with a regex alone. You would need a list of codes per city and compare the two fields in code.
- Why does 44 000 with a space fail?
- Postal codes are written as one block of five digits. Remove spaces before checking if users tend to type them.
- Is the same pattern valid for other countries?
- Several countries also use five-digit codes, so the shape is not unique to Pakistan. The address country field tells you which rule to apply.