Regex for IPv4 Address
This regex matches valid IPv4 addresses by validating each of the four octets is between 0 and 255. It correctly rejects values like 256.1.1.1 or 999.999.999.999 that simpler patterns would match. Each octet allows optional leading zeros and single-digit values. The pattern is commonly used in network configuration validation and log file parsing.
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$ What is the regex pattern for IPv4 Address?
The regex pattern for IPv4 Address is ^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$. This regex matches valid IPv4 addresses by validating each of the four octets is between 0 and 255. It correctly rejects values like 256.1.1.1 or 999.999.999.999 that simpler patterns would match. Each octet allows optional leading zeros and single-digit values. The pattern is commonly used in network configuration validation and log file parsing. This pattern is commonly used for network configuration validation and log file parsing.
Test Examples
192.168.1.1 192.168.1.1 255.255.255.0 255.255.255.0 999.999.999.999 Common Uses
- ✓ Network configuration validation
- ✓ Log file parsing
- ✓ Firewall rule validation
- ✓ API input sanitization
Variations
Simple (no range check)
^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ Matches format but allows invalid octets like 999
With CIDR notation
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\/(?:3[0-2]|[12]?\d)$ Matches IP with subnet mask like 192.168.1.0/24
Private ranges only
^(?:10\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.).*$ Matches only RFC 1918 private addresses
Frequently Asked Questions
Why not just use a simple digit pattern for IP addresses?
A simple pattern like \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} would match invalid addresses like 999.999.999.999. This regex validates each octet is in the 0-255 range, which is essential for correct IP address validation.
Does this match IPv6 addresses?
No, this pattern only matches IPv4 addresses. IPv6 uses a completely different format with hexadecimal groups separated by colons. See the IPv6 Address pattern for that.
Can this match IP addresses embedded in text?
As written with ^ and $ anchors, it matches the entire string. Remove the anchors to find IP addresses within larger text.