Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the start of the string | Start of '192.168.1.1' |
(?: |
Non-capturing group start (Python-specific) | Groups '[0-9]{1,3}\\.', but does not capture |
[0-9] |
Character class: matches any digit (0-9) | Digit '1' in '192' |
{1,3} |
Quantifier: matches 1 to 3 occurrences of the preceding element | Digits '168' in '168' |
\. |
Escaped literal dot (matches a single '.') | Dot '.' in '192.' |
) |
Non-capturing group end | End of group for '[0-9]{1,3}\\.' |
{3} |
Quantifier: matches exactly 3 occurrences of the preceding non-capturing group | Three groups like '192.', '168.', '1.' |
[0-9] |
Character class: matches any digit (0-9) | Digit '1' in '1' |
{1,3} |
Quantifier: matches 1 to 3 occurrences of the preceding element | Digits '1' in '1' |
$ |
Anchor: asserts the end of the string | End of '192.168.1.1' |
Matches
0.0.0.0255.255.255.255192.168.1.11.2.3.4123.45.67.89
Does not match
256.1.1.1192.168.1192.168.1.1.1192.168.1..192.168.1.1192.168.01.1192.168.1.a192.168.1.1
Common pitfalls
- Does not validate octet ranges (e.g., 256 is invalid but matches the pattern).
- Does not account for leading zeros (e.g., '01' is technically invalid in strict IPv4 notation).
- Fails if the string contains trailing whitespace or newlines (use re.MULTILINE or strip input).
- Overly permissive for octet values (e.g., '999' is matched but invalid).
- Does not handle IPv4-mapped IPv6 addresses (e.g., '::ffff:192.168.1.1').
Performance notes
No catastrophic backtracking risk due to fixed quantifiers and no alternations. Anchors (^ and $) ensure the entire string is checked, avoiding partial matches. For large inputs, pre-filter strings containing non-digit characters to improve performance.