Hong Kong HKID Number Regex for Python
/^([A-Z]{1,2})([0-9]{6})\(([0-9A])\)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching hong kong hkid number, ported and verified for Python. Identity and credential patterns need both correctness and safety, since they're frequent targets for adversarial input. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# Hong Kong HKID Number
# ReDoS-safe | RegexVault — Identity & PII > National Identity Numbers
import re
hong_kong_hkid_number_pattern = re.compile(r'^([A-Z]{1,2})([0-9]{6})\(([0-9A])\)$')
def validate_hong_kong_hkid_number(value: str) -> bool:
return bool(hong_kong_hkid_number_pattern.fullmatch(value))
# Example
print(validate_hong_kong_hkid_number("A123456(7)")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
A123456(7) | A1234567 |
AB123456(3) | A12345(7) |
Z999999(A) | A1234567(7) |
A123456(0) | 123456(7) |
| — | A123456(B) |
When to use this pattern
This pattern is drawn from the Identity & PII > National Identity Numbers category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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
Check character A represents 10 in the checksum. One-letter prefixes (A-Z) are issued chronologically; two-letter prefixes (AA-ZZ) started when the single-letter range was exhausted. Some older cards use lowercase or different formats.
Technical Notes
Structure: 1-2 uppercase letters + 6 digits + check character (0-9 or A) in parentheses. A single letter prefix is padded with a space for checksum calculation. The check character is computed via weighted sum mod 11.
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