public bool IsValidIP(string ip) { if (System.Text.RegularExpressions.Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")) { string[] ips = ip.Split('.'); if (ips.Length == 4 || ips.Length == 6) { if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256) return true; else return false; } else { return false; } } else { return false; } }if (IsValidIP("输入的字符串")) { Response.Write("对的"); } else { Response.Write("错的"); }
不严格的检查[\d]{1-3}\.[\d]{1-3}\.[\d]{1-3}\.[\d]{1-3}正则这样写也就够了严格的检查,判断每段为0-255(((2[0-4]\d)|(25[0-5]))|(1\d{2})|([1-9]\d)|(\d))[.](((2[0-4]\d)|(25[0-5]))|(1\d{2})|([1-9]\d)|(\d))[.](((2[0-4]\d)|(25[0-5]))|(1\d{2})|([1-9]\d)|(\d))[.](((2[0-4]\d)|(25[0-5]))|(1\d{2})|([1-9]\d)|(\d))代码:private bool IsIpAddress(string ipAddress){ string pattern = @"[\d]{1-3}\.[\d]{1-3}\.[\d]{1-3}\.[\d]{1-3}"; return Regex.IsMatch(ipAddress, pattern);}