Indonesian KTP (Kartu Tanda Penduduk) NIK Regex for Python
/^[1-9][0-9]{1}[0-9]{2}[0-9]{2}((?:(?:[04][1-9]|[1256][0-9]|[37][01])|(?:[04][1-9]|[1256][0-9]|[37][01])))(0[1-9]|1[0-2])(\d{2})(\d{4})$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching indonesian ktp (kartu tanda penduduk) nik, 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
# Indonesian KTP (Kartu Tanda Penduduk) NIK
# ReDoS-safe | RegexVault — Identity & PII > National Identity Numbers
import re
indonesian_ktp_kartu_tanda_penduduk_nik_pattern = re.compile(r'^[1-9][0-9]{1}[0-9]{2}[0-9]{2}((?:(?:[04][1-9]|[1256][0-9]|[37][01])|(?:[04][1-9]|[1256][0-9]|[37][01])))(0[1-9]|1[0-2])(\d{2})(\d{4})$')
def validate_indonesian_ktp_kartu_tanda_penduduk_nik(value: str) -> bool:
return bool(indonesian_ktp_kartu_tanda_penduduk_nik_pattern.fullmatch(value))
# Example
print(validate_indonesian_ktp_kartu_tanda_penduduk_nik("3171011504890001")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
3171011504890001 | 01710115040890001 |
1234015001990001 | 317101150489000 |
3273046501010001 | ABCD011504890001 |
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
For female residents, the day of birth has 40 added (e.g., born on the 5th → day code 45). This means day codes 41-71 indicate female. NIK validation requires both format and checksum validation.
Technical Notes
NIK structure: 2-digit province code (11-99) + 2-digit city/regency + 2-digit district + 2-digit day/gender (women have +40 to day) + 2-digit month + 2-digit year + 4-digit sequence. Female DOB: day+40 encodes gender.
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