🔍Regex Recipes
IPv4 Address Validation
Strict IPv4 address validation ensuring each octet is 0-255.
Pattern
^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$Explanation
Validates IPv4 addresses with strict octet validation (0-255). Each octet can be 1-3 digits.
Examples
Valid IP
Input
192.168.1.1
Output
✓ Match
Valid IP
Input
255.255.255.255
Output
✓ Match
Valid IP
Input
0.0.0.0
Output
✓ Match
Invalid - octet > 255
Input
256.1.1.1
Output
✗ No match
Invalid - missing octet
Input
192.168.1
Output
✗ No match
Code Examples
JavaScript
const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const isValidIPv4 = ipv4Regex.test('192.168.1.1'); // true Python
import ipaddress
# Better to use built-in library
try:
ip = ipaddress.IPv4Address('192.168.1.1')
print(f'Valid IP: {ip}')
except ipaddress.AddressValueError:
print('Invalid IP')Try it Now
💡 Tips
- Use built-in IP address libraries when possible
- Check for reserved ranges (127.0.0.0/8, 10.0.0.0/8, etc.)
- Consider if you need to support CIDR notation
- Validate each octet is truly 0-255
⚠️ Common Pitfalls
- Leading zeros may be interpreted as octal in some contexts
- Does not validate if IP is routable or reserved
- Does not check CIDR notation
- Consider using IP address libraries for production