Regex for IPv4 and IPv6 Address Matching
Regex patterns for matching IPv4 addresses (with optional range validation) and IPv6 addresses. Includes practical examples and common pitfalls to avoid.
Detailed Explanation
IP Address Matching with Regex
Matching IP addresses requires different approaches for IPv4 and IPv6 formats.
Basic IPv4 Pattern
\b\d{1,3}(?:\.\d{1,3}){3}\b
This matches the general format but does NOT validate that each octet is in the 0-255 range. It will match invalid addresses like 999.999.999.999.
Validated IPv4 Pattern
To validate each octet is between 0 and 255:
\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b
Breaking down the octet pattern:
25[0-5]matches 250-2552[0-4]\dmatches 200-249[01]?\d\d?matches 0-199
IPv4 with CIDR Notation
To match IP addresses with optional subnet mask:
\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:/[0-9]{1,2})?\b
Matches: 192.168.1.0/24, 10.0.0.1/8
Basic IPv6 Pattern
IPv6 addresses are much more complex due to abbreviation rules:
(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}
This only matches full-form IPv6. Abbreviated forms with :: require significantly more complex patterns.
Practical Advice
For production use, consider using your language's built-in IP parsing functions rather than regex. In JavaScript, you can parse and validate IPs more reliably with dedicated libraries or the URL constructor.
Use Case
You are parsing server logs to extract IP addresses, building a network tool that needs to validate IP input, or scanning configuration files for hardcoded IP addresses that should be moved to environment variables.