参考
方法
http://www.cnblogs.com/winnxm/archive/2008/12/15/1355111.html
优化后的表达式兼容ipv4、ipv6
方法
///
<summary>
/// 检查输入是否为ip地址字符串
/// </summary>
/// <param name="input"> 输入字符串 </param>
/// <returns></returns>
private static bool IsIPAddress( string input)
{
// 原作者表达式@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"
return Regex.IsMatch(input, @" ^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])((\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}|(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){5})$ ");
}
/// 检查输入是否为ip地址字符串
/// </summary>
/// <param name="input"> 输入字符串 </param>
/// <returns></returns>
private static bool IsIPAddress( string input)
{
// 原作者表达式@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"
return Regex.IsMatch(input, @" ^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])((\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}|(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){5})$ ");
}
测试
static
void Main(
string[] args)
{
bool bt = IsIPAddress( " 192.168.0.0 ");
bt = IsIPAddress( " 192.168.2.3.1.1 ");
bt = IsIPAddress( " bd5.168.2.1 ");
bt = IsIPAddress( " 192.168.254.10 ");
bt = IsIPAddress( " 192.168.254.10.1.1.1.1 ");
bt = IsIPAddress( " 192.168.254.10.1.1.1 ");
{
bool bt = IsIPAddress( " 192.168.0.0 ");
bt = IsIPAddress( " 192.168.2.3.1.1 ");
bt = IsIPAddress( " bd5.168.2.1 ");
bt = IsIPAddress( " 192.168.254.10 ");
bt = IsIPAddress( " 192.168.254.10.1.1.1.1 ");
bt = IsIPAddress( " 192.168.254.10.1.1.1 ");