Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '192.168.1.1' |
(?: |
Non-capturing group start (for grouping without capturing) | Start of the first octet group |
(?: |
Non-capturing group start (for grouping without capturing) | Start of the first octet pattern |
25[0-5] |
Matches numbers 250-255 | 250, 255 |
| |
Alternation (OR operator) | Separates 25[0-5] from 2[0-4][0-9] |
2[0-4][0-9] |
Matches numbers 200-249 | 200, 249 |
| |
Alternation (OR operator) | Separates 2[0-4][0-9] from [01]?[0-9][0-9]? |
[01]?[0-9][0-9]? |
Matches numbers 0-199 with optional leading zero | 0, 1, 10, 99, 199 |
) |
End of non-capturing group (for the first octet pattern) | End of the first octet pattern |
\. |
Escaped dot: matches a literal dot (.) | The dot in '192.168.1.1' |
){3} |
Quantifier: matches the preceding group exactly 3 times | The three dots in '192.168.1.1' |
(?: |
Non-capturing group start (for the last octet pattern) | Start of the last octet pattern |
25[0-5] |
Matches numbers 250-255 | 250, 255 |
| |
Alternation (OR operator) | Separates 25[0-5] from 2[0-4][0-9] |
2[0-4][0-9] |
Matches numbers 200-249 | 200, 249 |
| |
Alternation (OR operator) | Separates 2[0-4][0-9] from [01]?[0-9][0-9]? |
[01]?[0-9][0-9]? |
Matches numbers 0-199 with optional leading zero | 0, 1, 10, 99, 199 |
) |
End of non-capturing group (for the last octet pattern) | End of the last octet pattern |
$ |
Anchor: asserts the position at the end of the string | End of '192.168.1.1' |
Matches
0.0.0.01.2.3.4192.168.1.1255.255.255.25510.0.0.1
Does not match
256.1.1.1192.168.1192.168.1.1.1192.168.01.11.2.3.4.5abc.def.ghi.jkl192.168.1.01
Common pitfalls
- Forgetting to escape the dot (.) in the regex, which would match any character instead of a literal dot.
- Not accounting for leading zeros in octets (e.g., '01' is invalid unless it's a single digit like '1').
- Overlooking the requirement for exactly 4 octets separated by dots.
- Assuming the regex matches all valid IPv4 addresses without considering edge cases like '0.0.0.0' or '255.255.255.255'.
Performance notes
The regex is efficient for its purpose as it uses non-capturing groups and avoids catastrophic backtracking. However, it is not optimized for very long strings (e.g., 1MB+), where simpler patterns or native IP validation might be preferable.