首页 > 代码库 > 正则表达式匹配IP

正则表达式匹配IP

 static void Main(string[] args)
        {
            //择一匹配,查找数字或字母
            //string s="ad是是fs地dff22天{!@!~}}sdfsdffffcz";
            //string pattern =@"\d|[a-z]";//表达式(匹配所有数字或小写字母)
            //MatchCollection col = Regex.Matches(s, pattern);//Matches方法,每一个匹配上的结果存入col中。
            //foreach (Match m in col)//遍列出col中的Match
            //{
            //    Console.WriteLine(m);
            //}

            //将人名输出
            //string s1 = "zhangsan;lisi,wangwu.zhaolliu";
            //// string pattern1 = @"[;,.]";//[]匹配
            //string pattern1 = @"[;]|[,]|[.]";//择一匹配
            //string[] res= Regex.Split(s1, pattern1);
            //foreach (string s2 in res)
            //{
            //    Console.WriteLine(s2);
            //}


            //校验国内电话号码是否合法(方式一:010-87654321;方式二:(010)87654321)
            //string[] TellNumBer = new string[8];
            //TellNumBer[0] = "(010)87654321";
            //TellNumBer[1] = "010-87654321";
            //TellNumBer[2] = "01087654321";
            //TellNumBer[3] = "09087654321";
            //TellNumBer[4] = "(090)87654321";
            //TellNumBer[5] = "090-87654321";
            //TellNumBer[6] = "(09087654321";
            //TellNumBer[7] = "91287654321";
            //Regex RegexTellNumber = new Regex(@"\(0\d{2,3}\)\d{7,8}|^0\d{2,3}\-\d{7,8}$");
            //foreach (string Tell in TellNumBer)
            //{
            //    Console.WriteLine(Tell + "是否合法:" + RegexTellNumber.IsMatch(Tell));
            //}

            //重复 多个字符 使用(abcd){n}进行分组限定
            //string strGroup = @"(ab\w{2}){2}";//ab+两个数字并重复两次
            //string s3 = "ab12ab3233ab34ab45";
            //Regex RegexGroup = new Regex(strGroup);
            //Console.WriteLine(RegexGroup.Replace(s3,"replace"));//将满足条件的替换掉

            //校验IP4地址是否合法
            //2[0-4]\d      第一位为2时,第二位可为0-4
            //25[0-5]  或者一二位为25时,第三位为0-5
            //[01]?\d\d?  或者第一位的0或1出现1次或0次时,第二\d,第三位\d出现0或1次
            //\. 点
            //{3}上面的重复出现3次
            //(2[0-4]\d|25[0-5]|[01]?\d\d?) 判断第4位IP的情况
            string PatternIP = @"^(((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))$";
            string IP = "8.168.1.111";
            Regex RegexIp = new Regex(PatternIP);
            Console.WriteLine(RegexIp.IsMatch(IP));
            Console.ReadKey();


        }

 

正则表达式匹配IP