Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of input |
(?: |
Non-capturing group start (outer alternation group) | Start of either IPv4 or IPv6 pattern |
(?: |
Non-capturing group start (IPv4 segment group) | Start of IPv4 segment repetition |
\d |
Digit character class (0-9) | 0, 5, 9 |
{1,3} |
Quantifier: match between 1 and 3 of the preceding token (digits) | 1, 12, 123 |
\. |
Literal dot character (escaped) | . |
){3} |
Quantifier: repeat the preceding group (digits followed by dot) exactly 3 times | 192.168.1. |
\d |
Digit character class (0-9) | 0, 5, 9 |
{1,3} |
Quantifier: match between 1 and 3 of the preceding token (digits) | 1, 12, 123 |
) |
End of IPv4 segment group | End of IPv4 segment |
| |
Alternation: separates two alternatives in the outer group | OR operator between IPv4 and IPv6 |
(?: |
Non-capturing group start (IPv6 segment group) | Start of IPv6 segment repetition |
(?: |
Non-capturing group start (single IPv6 segment) | Start of a single IPv6 segment |
[0-9a-fA-F] |
Hexadecimal digit character class (case-insensitive) | 0, a, F, 9 |
{1,4} |
Quantifier: match between 1 and 4 of the preceding token (hex digits) | 0, ab, 1234, FFFF |
: |
Literal colon character | : |
){7} |
Quantifier: repeat the preceding group (hex segment followed by colon) exactly 7 times | 2001:0db8:85a3:0000:0000:8a2e:0370:7334: |
[0-9a-fA-F] |
Hexadecimal digit character class (case-insensitive) | 0, a, F, 9 |
{1,4} |
Quantifier: match between 1 and 4 of the preceding token (hex digits) | 0, ab, 1234, FFFF |
) |
End of IPv6 segment group | End of IPv6 address |
$ |
Anchor: asserts position at end of the string | End of input |
Matches
192.168.1.110.0.0.12001:0db8:85a3:0000:0000:8a2e:0370:73342001:db8:85a3:0:0:8a2e:370:73340:0:0:0:0:0:0:1127.0.0.1
Does not match
256.1.1.1192.168.1192.168.1.1.12001:0db8:85a3::8a2e:0370:73342001:db8:85a3:0:0:8a2e:370127.0.0example.com192.168.1.1:80
Common pitfalls
- Does not match compressed IPv6 addresses (e.g., with ::)
- Does not validate IP ranges (e.g., 256.0.0.1 passes digit check but is invalid)
- Does not account for leading/trailing whitespace (anchors ^ and $ prevent this)
- Does not handle mixed-case IPv6 addresses beyond the character class (e.g., '2001:0DB8...' is valid due to case-insensitive class)
Performance notes
The pattern is linear in complexity for both IPv4 and IPv6 branches, with no nested quantifiers that could cause catastrophic backtracking. The alternation is simple and does not introduce significant overhead. Ensure input is trimmed if whitespace is a concern, as ^ and $ anchors will not match otherwise.