Regex for IP Address Validation — IPv4 & IPv6
Quick Answer: IPv4 regex: ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$. IPv6 is much harder to regex due to abbreviation rules. For production, use net.ParseIP() (Go), ipaddress module (Python), or similar built-in validators.
FAQ
Why is IPv6 regex so complex?
IPv6 allows abbreviations: leading zero suppression and :: for consecutive zero groups. A full regex must handle all valid abbreviation combinations across 8 groups.
How do I validate CIDR notation?
Append /\d{1,2} for IPv4 CIDR (e.g., 192.168.1.0/24) or /\d{1,3} for IPv6. Validate the prefix length is within range (0-32 for v4, 0-128 for v6).