Regex for IPv4 Address Validation — Pattern with Examples

Strict regex for IPv4 address validation that rejects 256+ octets. Pattern, edge cases, and tested examples for log parsing, firewall rules, and form validation.

Data Validation

Detailed Explanation

Regex for IPv4 Address Validation

IPv4 addresses are defined in RFC 791 as a sequence of four octets separated by dots, with each octet ranging 0–255. A naive pattern like \d{1,3}(\.\d{1,3}){3} will match 999.999.999.999 and other invalid input, so for real validation each octet must be range-checked.

Strict Pattern

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

The octet sub-pattern handles three numeric ranges:

Sub-pattern Range
25[0-5] 250–255
2[0-4][0-9] 200–249
[01]?[0-9][0-9]? 0–199

The ^ and $ anchors prevent partial matches such as 192.168.1.1.foo.

Tested Examples

Input Matches?
192.168.1.1 yes
10.0.0.255 yes
0.0.0.0 yes
256.0.0.1 no (256 > 255)
192.168.1 no (only 3 octets)
192.168.01.1 yes (leading zero allowed)

Edge Cases

  • Leading zeros: This pattern accepts 01 and 001, which strict RFC-compliant parsers reject because they look like octal. To forbid them, use (25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).
  • Whitespace: Use \b instead of ^/$ to extract IPs from text without trimming.
  • CIDR: Append (/(3[0-2]|[12]?[0-9]))? to allow optional /24-style suffixes.

Practical Notes

For production code, prefer net.isIPv4() in Node.js or ipaddress in Python. Reserve regex for log scraping and quick filters where a dependency-free check is enough.

Use Case

Extracting client IPs from web server logs, validating allowlist/denylist entries in a firewall configuration UI, or scrubbing IP addresses from support tickets before sharing with third parties.

Try It — Regex Cheat Sheet

Open full tool