Regex patterns/Validation
IPv4 address
Four numbers, each genuinely 0–255 — not the \d{1,3} version that accepts 999.
/^(?:(?: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)$/The problem
Check that a string is a dotted-quad IPv4 address with every octet in range.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^(?:(?:25[0-5]|2[0-4]…In order:^The start of the text (or of a line with the m flag)(?:(?:25[0-5]|2[0-4]\…Repeated exactly 3 times, as many as possible:(?:(?:25[0-5]|2[0-4]\…Group (not captured):(?:25[0-5]|2[0-4]\d|1…In order:(?:25[0-5]|2[0-4]\d|1…Group (not captured):25[0-5]|2[0-4]\d|1\d\…Any one of these alternatives:25[0-5]In order:2The character "2"5The character "5"[0-5]Any one of: "0" to "5"2[0-4]\dIn order:2The character "2"[0-4]Any one of: "0" to "4"\dA digit1\d\dIn order:1The character "1"\dA digit\dA digit[1-9]?\dIn order:[1-9]?Any one of: "1" to "9", optionally (zero or one time)\dA digit\.The character "."(?:25[0-5]|2[0-4]\d|1…Group (not captured):25[0-5]|2[0-4]\d|1\d\…Any one of these alternatives:25[0-5]In order:2The character "2"5The character "5"[0-5]Any one of: "0" to "5"2[0-4]\dIn order:2The character "2"[0-4]Any one of: "0" to "4"\dA digit1\d\dIn order:1The character "1"\dA digit\dA digit[1-9]?\dIn order:[1-9]?Any one of: "1" to "9", optionally (zero or one time)\dA digit$The end of the text (or of a line with the m flag)
Matches
- 192.168.0.1
- 255.255.255.255
- 0.0.0.0
- 8.8.8.8
Does not match
- 256.1.1.1
- 10.0.0
- 1.2.3.4.5
- 01.02.03.04.05
Where it bites
- The alternatives must be ordered from most specific to least: put [1-9]?\d first and 25[0-5] never gets a chance, because the engine takes the first branch that fits.
- It accepts leading zeros in some positions (010 reads as 10), which some parsers treat as octal.
- IPv6 needs a completely different pattern; this one does not attempt it.