Reputation: 49
I have string in format:
172.60.136.145,172.60.136.146,172.60.136.147,........
and I need help in validating the IpAddresses in the string using Regex
Upvotes: 1
Views: 118
Reputation: 17858
For specific such as above
172\.60\.136\.[0-9]{1-3}
which nails it specifically to the range of 172.60.136.0 through 999
of course that doesnt cover valid only IPs, that would allow 172.60.136.0 or 172.60.136.999
(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])(\\.(0?0?[0-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])){2}(\\.(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))
Does test that the IP is valid, it allows 1.0.0.1, through 254.254.254.254, wont allow anything ending in .0 etc.
Upvotes: 4
Reputation: 32936
I'm not sure regex is your best option here as ip addresses are only valid if the numbers are 254 or less
I would split the string at the commas and then split each one of those by a period. I would check that there are 4 sections and that each section can be converted to a number which is 254 or less.
something like this untested pseudo code
string[] addresses = myString.Split(",");
foreach(string address in addresses)
{
string[] numbers = address.Split(".");
if (numbers.Length==4)
{
Foreach(string number in numbers)
{
// need to check that the last number is not a zero as well - not shown here
int value = Convert.ToInt32(number);
if (value<0 && value>254)
{
//invalid
}
}
}
else
{
//invalid
}
}
there are probably classes you could use in your language to help with this but you don't say what language it is. You could do this in c#:
string[] addresses = myString.Split(",");
foreach(string address in addresses)
{
IpAddress ipAddress;
if (!IpAddress.TryParse(address, out ipAddress))
{
//invalid
}
}
if you just wanted to invalid ones you could do:
IPAddress ipAddress;
string[] addresses = myString.Split (",");
foreach (string address in addresses.Where (address => !IPAddress.TryParse (address, out ipAddress)))
{
//all elements in this loop will be invalid entries
// remove the '!' to get only the valid ones
}
Upvotes: 0
Reputation: 131961
In PHP:
$tmp = explode(',', $ips);
$tmp = array_map('ip2long', $tmp);
if (array_search(false, $tmp, true) !== false) {
// at least one ip is invalid
}
Upvotes: 1