IPv4 Address (Strict 0–255) Regex for Python
/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/What this pattern does
Validating strict IPv4 addresses is a common task, and this Python regex gives you a robust solution. The pattern ensures that each octet falls within the 0-255 range, rejecting invalid addresses like 256.0.0.1 or 192.168.1.01. Use this regular expression wherever you need to rigorously validate IPv4 inputs, such as in web form data processing or network configuration scripts.
Python Implementation
# IPv4 Address (Strict 0–255)
# ReDoS-safe | RegexVault — Web & Network > IPv4
import re
ipv4_address_strict_0255_pattern = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$')
def validate_ipv4_address_strict_0255(value: str) -> bool:
return bool(ipv4_address_strict_0255_pattern.fullmatch(value))
# Example
print(validate_ipv4_address_strict_0255("0.0.0.0")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
0.0.0.0 | 256.1.1.1 |
192.168.1.1 | 192.168.1 |
255.255.255.255 | 192.168.1.1.1 |
10.0.0.1 | 192.168.01.1 |
172.16.254.1 | not.an.ip.addr |
When to use this pattern
ReDoS vulnerabilities pose a real threat to Python applications, particularly those exposed to untrusted user input. A poorly designed regex can consume excessive CPU resources, leading to denial-of-service conditions. This ReDoS-safe IPv4 pattern helps protect against such attacks by preventing catastrophic backtracking. Integrating this pattern into your Django or Flask project gives you confidence to deploy to production.
Common Pitfalls
Using \d{1,3} instead of the strict alternation allows values like 999 or 256. Do not use [0-9]{1,3} — it accepts out-of-range octets.
Technical Notes
The alternation order in each octet group (25[0-5] first, then 2[0-4], then 1xx, then [1-9][0-9], then single digit) is critical for correctness. Reordering breaks range enforcement. Leading zeros are rejected because 01 does not match any branch.
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