# Regex for IPv4 Address Validation

> IPv4 regex that enforces the 0–255 range per octet and rejects leading zeros, explained token by token with match examples.

```
/^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/
```

The naive \d{1,3}(\.\d{1,3}){3} accepts 999.999.999.999, so a correct IPv4 pattern has to spell out the 0–255 range as alternatives: 250–255, 200–249, 100–199, and 0–99. This pattern does that for each of the four octets and rejects leading zeros (01.2.3.4), which some parsers dangerously interpret as octal.

## Token by token

| Token | Meaning |
|---|---|
| `25[0-5]` | 250 through 255 |
| `2[0-4]\d` | 200 through 249 |
| `1\d\d` | 100 through 199 |
| `[1-9]?\d` | 0 through 99, with no leading zero |
| `(\.(…)){3}` | a dot plus the same octet alternatives, exactly three more times |

## Examples

- ✓ matches: `192.168.0.1`
- ✓ matches: `255.255.255.255`
- ✓ matches: `8.8.8.8`
- ✗ does not match: `256.1.1.1`
- ✗ does not match: `192.168.1`
- ✗ does not match: `01.2.3.4`

## Variations

- `^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\/(3[0-2]|[12]?\d)$` — CIDR notation: the address plus /0 through /32
- `\b(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\b` — unanchored with word boundaries — extract addresses from logs with the g flag

## Language notes

- Why reject leading zeros? inet_aton and some parsers read 010 as octal 8 — a classic SSRF filter bypass.
- When a parser is available (ipaddress in Python, net.ParseIP in Go), prefer it — you get range checks and normalization for free.

## FAQ

### Why is the naive \d{1,3} pattern wrong?

It matches any three digits per octet, so 999.999.999.999 passes. IPv4 octets top out at 255, and expressing 'a number from 0 to 255' in regex requires the explicit alternatives this pattern uses.

### Does this match IPv6 too?

No — IPv6 is a completely different format (hex groups separated by colons). See the IPv6 pattern for that; and if you need to accept both, test against the two patterns separately.

## Related patterns

- [Regex for IPv6 Address Validation](https://www.devkult.com/regex/ipv6.md)
- [Regex for URL Validation](https://www.devkult.com/regex/url.md)
- [Regex for UUID Validation](https://www.devkult.com/regex/uuid.md)

Open the interactive page: https://www.devkult.com/regex/ipv4