How to Match an IPv4 Address with Regex
Validating an IPv4 address is one of the most common tasks in network programming and log parsing. A standard IPv4 address consists of four octets, ranging from 0 to 255, separated by dots.
The Pattern Breakdown
The regular expression ^(?:(?: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]?)$ looks complex, but it simply enforces the mathematical rules of an IP address:
25[0-5]: Matches numbers 250 through 255.2[0-4][0-9]: Matches numbers 200 through 249.[01]?[0-9][0-9]?: Matches numbers 0 through 199.
Common Use Cases
- Log Parsing: Extracting client IPs from Nginx or Apache access logs.
- Firewall Rules: Validating user input in security configurations.
- Data Cleaning: Sanitizing CSV files containing server metadata.