//从字符串中提取所有ip地址
public static List<string> GetIPAddresses(string str)
{
List<string> ips = new List<string>();
Regex re = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
MatchCollection mx = re.Matches(str);
foreach (Match item in mx)
{
if (!ips.Contains(item.Value) && item.Value!="0.0.0.0")
ips.Add(item.Value);
}
return ips;
}
public static bool IsIPAddress(string str)
{
if (str == null || str == string.Empty || str.Length < 7 || str.Length > 15) return false;
string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace IPCheck
{
class Program
{
static void Main(string[] args)
{
List<string> ipList = new List<string>();
ipList.Add("1.13.3.3");
ipList.Add("9,i");
ipList.Add("999,43,4");
ipList.Add("888.168.4.5");
ipList.Add("192.168.0.4");
ipList.Add(" fdb2: 2c26: f4e4: 0:f46d: 3d07:8abc: a9dd");
ipList.Add("fdb2:2c26:f4e4:0:f46d:3d07:8abc:a9dd");
IPAddress ip;
foreach(var ipstring in ipList)
{
if(IPAddress.TryParse(ipstring,out ip))
{
Console.WriteLine("{0} is a ipaddress, value is {1}", ipstring, ip.ToString());
}
else
{
Console.WriteLine("{0} is not a ipaddress!", ipstring);
}
}
Console.WriteLine("正则验证开始……");
foreach(var ipstr in ipList)
{
if(IsIPAddress(ipstr))
{
Console.WriteLine("{0} is a ipaddress", ipstr);
}
else
{
Console.WriteLine("{0} is not a ipaddress!", ipstr);
}
}
Console.Read();
}
public static bool IsIPAddress(string str)
{
if (str == null || str == string.Empty || str.Length < 7 || str.Length > 15) return false;
string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str);
}
}
}
以上测试得出以下结论:
1.上面的正则验证是不准确的的,不管是ipv4,还是ipv6都不准
2.IpAddress.tryparse可以验证字符串是不是ipv4地址
3.进行字符串验证时,要对字符串进行去空格处理,当然如果是为了验证字符串的正确性,另当别论。