Friday, February 16, 2018

Regex: Valid IP Address

How to create a regular expression that will check if an IP is valid.

What is a valid IPv4 address? It is an address that has four parts each separated by a dot "." and each part having a value from 0 to 255. Example:


Since you have four repeating numeric ranges [0-255], lets start by focusing on that one range. First break the [0-255] numeric range into smaller numeric ranges that still fall into the larger numeric range that we can easily convert to regular expression ranges.

[0-9], [10-99], [100-199], [200-249], and [250-255]

Next, we need to convert these numeric ranges into regular expression ranges. Note, a regular expression (regex) range of [0-9] and \d mean the same thing.

Numeric       Regex
[0-9]      =  \d
[10-99]    =  [1-9]\d
[100-199]  =  1\d\d
[200-249]  =  2[0-4]\d
[250-255]  =  25[0-5]

Now, put the regex ranges together inside of round brackets "()" and place a "|" bar between each part to indicate "OR" conditions where one part of the condition makes the whole condition true. What you have now is a regular expression that allows for a numeric range of [0-255].


Next step is to allow four of these numeric ranges with a "." dot between them. To put a dot in regex, you will need to escape it "\." because a dot by itself "." means "any character" which could be non-numeric. Using our previous regular expression for [0-255], we repeat it four times and put a "\." between them.


This is quite long with the part for the ".[0-255]" numeric range repeating three times, so lets consolidate those pieces by placing one of them in round brackets "()" and adding curly brackets "{3}" to the end to indicate it should repeat three times.


One final step that we want to do is set it so the entire value has to match this regular expression by using the starting "^" and ending "$" characters. Note, some people replace the "^" and "$" characters with a word boundary "\b".


Here is an online regular expression checker.

No comments:

Post a Comment