Regular expressions for validating IPv4 and IPv6 address formats, supporting IP address validation needs in network programming and system administration
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
- Matches numbers 0-25525[0-5]
- Matches 250-2552[0-4][0-9]
- Matches 200-249[01]?[0-9][0-9]?
- Matches 0-199\.3
- Matches three dot separators^
and $
- Ensures complete match[0-9a-fA-F]4
- 1-4 hexadecimal digits:
- Colon separator{7}
- Repeat 7 times (8 groups)::1
- IPv6 loopback address::
- IPv6 zero address// IPv4 validation
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
function validateIPv4(ip) {
return ipv4Regex.test(ip);
}
// IPv6 validation
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;
function validateIPv6(ip) {
return ipv6Regex.test(ip);
}
// Usage examples
console.log(validateIPv4("192.168.1.1")); // true
console.log(validateIPv6("2001:0db8:85a3::8a2e:0370:7334")); // true
import re
# IPv4 validation
ipv4_pattern = r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
def validate_ipv4(ip):
return bool(re.match(ipv4_pattern, ip))
# IPv6 validation
ipv6_pattern = r'^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$'
def validate_ipv6(ip):
return bool(re.match(ipv6_pattern, ip))
# Usage examples
print(validate_ipv4("192.168.1.1")) # True
print(validate_ipv6("2001:0db8:85a3::8a2e:0370:7334")) # True
import java.util.regex.Pattern;
public class IPValidator {
// IPv4 validation
private static final String IPV4_PATTERN =
"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
private static final Pattern ipv4Pattern = Pattern.compile(IPV4_PATTERN);
public static boolean validateIPv4(String ip) {
return ipv4Pattern.matcher(ip).matches();
}
// IPv6 validation
private static final String IPV6_PATTERN =
"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$";
private static final Pattern ipv6Pattern = Pattern.compile(IPV6_PATTERN);
public static boolean validateIPv6(String ip) {
return ipv6Pattern.matcher(ip).matches();
}
}
Input | Type | Expected Result | Description |
---|---|---|---|
192.168.1.1 | IPv4 | ✓ Valid | Standard private IP address |
10.0.0.1 | IPv4 | ✓ Valid | Private network address |
172.16.0.1 | IPv4 | ✓ Valid | Private network address |
8.8.8.8 | IPv4 | ✓ Valid | Google DNS |
255.255.255.255 | IPv4 | ✓ Valid | Broadcast address |
0.0.0.0 | IPv4 | ✓ Valid | Default route |
256.1.1.1 | IPv4 | ✗ Invalid | Out of range |
192.168.1 | IPv4 | ✗ Invalid | Incomplete IP |
2001:0db8:85a3::8a2e:0370:7334 | IPv6 | ✓ Valid | Standard IPv6 address |
::1 | IPv6 | ✓ Valid | IPv6 loopback address |
:: | IPv6 | ✓ Valid | IPv6 zero address |
2001:db8::1 | IPv6 | ✗ Invalid | Simplified format (requires more complex regex) |