IP address regex
An IPv4 regex that checks each octet is 0–255, plus a simplified IPv6 pattern. Tested examples and code for JavaScript and Python.
Pattern
/^(?:(?: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)$/Matches
192.168.0.18.8.8.8255.255.255.255
Doesn't match
256.1.1.1192.168.01.11.2.31.2.3.4.5
Alternative: IPv6, full (uncompressed) form only
^(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$Notes
- Each octet is built from alternatives: 250–255, 200–249, 100–199, 0–99. Leading zeros are rejected, which avoids octal ambiguity in some parsers.
- IPv6 with :: compression has many forms; in Python use ipaddress.ip_address(), in Node net.isIP().
Code
JavaScript
const re = /^(?:(?: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)$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'(?:(?: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)', value))Try it on your own input
The live tester adds the g and m flags so every line is checked separately.
Questions
Why not just \d{1,3}(\.\d{1,3}){3}?
It accepts 999.999.999.999. Checking the 0–255 range needs the alternation used here.
More patterns
Email regexPhone number regexURL regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regexPassword regex