Validating IP Addresses with Regex (and Better Ways)
Regex can match the shape of an IP, but real validation (ranges, IPv6 compression) is better left to a parser.
IPv4 Regex
Each octet must be 0–255:
^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$
That already shows how fiddly it gets — and IPv6 regex (with :: compression and embedded IPv4) is far worse and error-prone.
Prefer a Parser
Most languages validate correctly in one line:
import ipaddress
def is_ip(s):
try: ipaddress.ip_address(s); return True
except ValueError: return False
ok := net.ParseIP(s) != nil
import net from "node:net";
const ok = net.isIP(s) !== 0; // 4, 6, or 0
See more in IP programming samples.
Use regex only for a quick format filter. For "is this a usable address, and is it in my allowed range?", use a parser plus CIDR check — try the subnet calculator to reason about ranges.