Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
( |
Start of a capturing group (group 1) | Start of group |
( |
Start of an alternation group (group 2) | Start of alternation |
25[0-5] |
Matches numbers 250-255 (25 followed by 0-5) | 250, 255 |
| |
Alternation: OR operator | Separates alternatives |
2[0-4][0-9] |
Matches numbers 200-249 (2 followed by 0-4, then 0-9) | 200, 249 |
| |
Alternation: OR operator | Separates alternatives |
[01]?[0-9][0-9]? |
Matches numbers 0-199 with optional leading zero (0-1 followed by 0-9, optionally followed by another 0-9) | 0, 5, 10, 99, 199 |
) |
End of alternation group (group 2) | End of alternation |
\. |
Escaped dot: matches a literal dot character | . |
) |
End of capturing group (group 1) | End of group |
{3} |
Quantifier: exactly 3 repetitions of the preceding group (group 1) | Three octets followed by dots |
( |
Start of an alternation group (group 3) | Start of alternation |
25[0-5] |
Matches numbers 250-255 (25 followed by 0-5) | 250, 255 |
| |
Alternation: OR operator | Separates alternatives |
2[0-4][0-9] |
Matches numbers 200-249 (2 followed by 0-4, then 0-9) | 200, 249 |
| |
Alternation: OR operator | Separates alternatives |
[01]?[0-9][0-9]? |
Matches numbers 0-199 with optional leading zero (0-1 followed by 0-9, optionally followed by another 0-9) | 0, 5, 10, 99, 199 |
) |
End of alternation group (group 3) | End of alternation |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
0.0.0.0192.168.1.1255.255.255.25510.0.0.1172.16.254.11.2.3.4
Does not match
256.1.2.3192.168.01.1192.168.1192.168.1.1.1abc.def.ghi.jkl192.168.1.-1192.168.001.001
Common pitfalls
- Leading zeros in octets (e.g., 192.168.001.001) are technically allowed by the regex but may be invalid in some contexts.
- The regex does not prevent leading zeros in octets like 01 or 001, which may be undesirable in strict IP validation.
- The regex does not account for IP addresses with extra leading dots or spaces.
- The regex does not validate the entire string if it contains trailing characters after the IP address.
Performance notes
The pattern is efficient for typical IPv4 validation as it uses simple alternations and quantifiers. However, catastrophic backtracking is not a concern here due to the fixed structure and lack of nested quantifiers. Anchoring with ^ and $ ensures the entire string is validated.