Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of '192.168.1.1' |
( |
Start of a non-capturing group (for alternation) | Group start before '25[0-5]' |
25 |
Literal characters '2' followed by '5' | Digits '25' in '255' |
[0-5] |
Character class matching digits 0-5 | Digit '5' in '255' |
| |
Alternation operator (OR) | Separates '25[0-5]' from '2[0-4][0-9]' |
2 |
Literal character '2' | Digit '2' in '249' |
[0-4] |
Character class matching digits 0-4 | Digit '4' in '249' |
[0-9] |
Character class matching any digit 0-9 | Digit '9' in '249' |
| |
Alternation operator (OR) | Separates '2[0-4][0-9]' from '[01]?[0-9][0-9]?' |
[01]? |
Optional character class matching '0' or '1' (0 or 1 occurrence) | Digit '0' or '1' in '099' or '192' |
[0-9] |
Character class matching any digit 0-9 | Digit '9' in '192' |
[0-9]? |
Optional digit (0 or 1 occurrence) | Digit '2' in '192' (optional in '92') |
) |
End of non-capturing group | Group end after '[01]?[0-9][0-9]?' |
\. |
Escaped literal dot (matches '.') | Dot between octets in '192.168.1.1' |
( |
Start of a non-capturing group (for repetition) | Group start before '25[0-5]' |
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) |
Same octet pattern as before (reused for repetition) | Octet like '255' or '192' |
\. |
Escaped literal dot (matches '.') | Dot in '192.168.1.1' |
){2} |
Quantifier: repeat the preceding group exactly 2 times | Matches two octet-dot pairs (e.g., '.168.1') |
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) |
Final octet pattern (same as first) | Last octet like '1' in '192.168.1.1' |
$ |
Anchor: asserts position at end of the string | End of '192.168.1.1' |
Matches
192.168.1.10.0.0.0255.255.255.25510.0.0.1172.16.254.1
Does not match
256.1.1.1192.168.1192.168.1.1.1192.168.01.1192.168.1.1a192.168.-1.1
Common pitfalls
- Fails to match leading zeros in octets (e.g., '192.168.001.001' is invalid in strict mode).
- Does not account for whitespace (e.g., ' 192.168.1.1 ' fails).
- Overly permissive with optional leading digits (e.g., '999' is invalid but may match if not anchored properly).
- Does not validate the entire string (e.g., '192.168.1.1extra' matches the first part but not the whole string).
Performance notes
The pattern is prone to catastrophic backtracking if not anchored properly (e.g., without ^ and $). The alternation and optional quantifiers can create many paths, but the anchors mitigate this. For very long strings, consider optimizing or using a dedicated IP validation library.