How to Validate IP Addresses Using Regular Expressions in Ruby
Like the email address matcher guide, we are going to build an IP matcher in this lesson using Ruby and regular expressions. An example of how this could be used would be building a security block and want to verify or block IP addresses.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Like the email address matcher guide, we are going to build an IP matcher in this lesson using Ruby and regular expressions. An example of how this could be used would be building a security module that verifies or block IP addresses in a program.

To do that, 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 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 email address validator.

def is_valid_ip_address? ip
  ip =~ IP_ADDRESS_REGEX
end

Next, we are going to 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"
"Valid"
"Valid"
"Invalid"

And that's the right output based on the sample data.

When working with regular expressions I find it helpful to use a tool called Rubular. Go to rubular.com and you'll find it's a pretty handy tool to create regular expressions in Ruby.

To test how these values work in Rubular, copy the regular expression and paste it in the web page. Also, copy each of the use cases and paste it against the column Your test string. If it is valid string, it should look like this:

large

If it is not a valid string, then the output should be:

large

This tool can be a great way to run different test strings. You can also experiment various regular expressions to get the results you want. There are also some quick reference expressions in the lower part of the page that you can use.

large