IP的正则表达式

  • Post author:
  • Post category:其他


IP的正则表达式

ipv4的格式:(1-255).(0-255).(0-255).(0-255)

1、方法一

0-99的正则表达式[1-9]?[0-9]

100-199的正则表达式1[0-9]{2}

200-249的正则表达式2[0-4][0-9]

250-255的正则表达式25[0-5]

ipv4的正则表达式:

([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(.([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}

2、方法二

1-9的正则表达式:[1-9]

10-99的正则表达式:[1-9]\d

100-199的正则表达式:1\d{2}

200-249的正则表达式:2[0-4]\d

250-255的正则表达式:25[0-5]

ipv4的正则表达式:

([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}

3、实现函数

/// <summary>
        /// ip格式检查
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static Boolean IsIpAddress(string ip)
        {
            //清除字符串中的空格
            ip = ip.Trim();
            //如果为空,不合格退出
            if (string.IsNullOrEmpty(ip))
            {
                return false;
            }
            //ip正则表达式
            string patten = @"^([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}$";
            //string patten = @"^([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$";
            //验证
            return Regex.IsMatch(ip, patten);
        }

4、函数调用

private void btSystemNetSave_Click(object sender, EventArgs e)
        {
            if (FormatCheck.IsIpAddress(this.tbNetControlIp.Text))
            {
                MessageBox.Show("Right");
            }
            else
            {
                MessageBox.Show("Error");
            }
        }



版权声明:本文为qq_27474555原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。