As promised, more regular expression fun. This week we're going to validate IP addresses. An IP address consists of four octets separated by periods. A lazy person might be inclined to use a regular expression of \d{1,3}
for each octet, but that would allow numbers larger than 255. A more complex expression is needed: ([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})
.
This expression consists of three parts separated by the pipe character "|". The first part, [1]?\d{1,2}
, matches numbers between 0 and 199. The second part, 2[0-4]{1}\d{1}
, matches numbers between 200 and 249. The third part, 25[0-5]{1}
, matches numbers between 250 and 255. We will repeat this pattern four times, once for each octet, and separate with periods.
ASP
function isValidIP(ip)
dim regEx
set regEx = new RegExp
with regEx
.IgnoreCase = True
.Global = True
.Pattern = "^([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})(\.([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})){3}$"
end with
if regEx.Test(trim(CStr(ip))) then
isValidIP = true
else
isValidIP = false
end if
set regEx = nothing
end function
PHP
function isValidIP($ip)
{
$pattern = "/^([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})(\.([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})){3}$/";
return (preg_match($pattern, $ip) > 0) ? true : false;
}
Next week we're going to build on this pattern to validate something else. I wonder what that could be?