How to validate an IP address using regular expressions
Now we'll build an IP matcher using Ruby and regular expressions. An example of how this could be used would be through building a security module that either verifies or blocks IP addresses in a program.
To do this, let's define a constant that will store the regular expression:
IP_ADDRESS_REGEX = /^((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){4})$/
This regular expression will take all the valid IP address values, which range from 172.16.0.0
to 172.31.255.255
.
The rest of the code is going to be fairly similar to the validator
email address:
def is_valid_ip_address? ip ip =~ IP_ADDRESS_REGEX end
Next, let's check some use cases:
p is_valid_ip_address? ("999.16.0.0") ? "Valid" : "Invalid" p is_valid_ip_address? ("172.16.0.0") ? "Valid" : "Invalid" p is_valid_ip_address? ("172.31.255.255") ? "Valid" : "Invalid" p is_valid_ip_address? ("172.31.255.256") ? "Valid" : "Invalid"
If you execute this code, your output will be:
"Invalid...