What Is a Good Regex for IPv4 Address Validation?
Pattern: ^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$. An IPv4 address consists of four octets (0-255) separated by dots. The correct regex must validate that each octet is within the valid range, not just that the format looks right. A naive approach using \d{1,3} would accept invalid addresses like 999.999.999.999.
Breaking Down the Pattern
| Part | Meaning |
|---|---|
^ | Start of string |
(25[0-5]|2[0-4]\d|[01]?\d\d?) | Match a number from 0 to 255 |
\. | Literal dot separator |
{3} | Repeat the octet+dot group 3 times |
(25[0-5]|2[0-4]\d|[01]?\d\d?)$ | Final octet (0-255), end of string |
Test Cases
| Input | Match? | Note |
|---|---|---|
192.168.1.1 | Yes | Valid format |
10.0.0.255 | Yes | Valid format |
0.0.0.0 | Yes | Valid format |
256.1.1.1 | No | 256 exceeds the 0-255 range |
192.168.1 | No | Only 3 octets instead of 4 |
Usage Examples
JavaScript
const pattern = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
pattern.test('192.168.1.1'); // true
pattern.test('256.1.1.1'); // false
Python
import re
pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'
bool(re.match(pattern, '192.168.1.1')) # True
bool(re.match(pattern, '256.1.1.1')) # False
Common Pitfalls
- A simple \d{1,3} pattern accepts 999.999.999.999 -- always validate the 0-255 range.
- This pattern does not distinguish between public and private IP ranges.
- Leading zeros (e.g., 192.168.01.001) may or may not be accepted depending on your use case.
Try It Yourself
Test this regex with our Regex Tester.
Frequently Asked Questions
What is the range of valid IPv4 addresses?
Each octet ranges from 0 to 255, giving addresses from 0.0.0.0 to 255.255.255.255. Special ranges include 127.0.0.0/8 (loopback), 10.0.0.0/8 (private), and 192.168.0.0/16 (private).
Should I use regex or a library to validate IPs?
For simple format checking, regex works. For production use, prefer language-specific libraries (e.g., Python ipaddress module, Node.js net.isIP()) that also handle edge cases like CIDR notation.
Does this regex match IPv6 addresses?
No. IPv6 addresses use a completely different format with hex groups separated by colons. Use a separate pattern for IPv6.