C#用正则表达式对IP进行排序

        static void Main(string[] args)
        {
            string IPs = "   192.168.1.1   202.47.4.6      1.2.3.3   ";
            Console.WriteLine(IPs);
            IPs = Regex.Replace(IPs, @"(\d+)", "00$1");//先给每个IP的数字加上00
            Console.WriteLine(IPs);
            IPs = Regex.Replace(IPs, @"0*(\d{3})", "$1");//然后将每个数字用它的后3位替换
            Console.WriteLine(IPs);

            string[] IParr = Regex.Split(IPs, @" +");
            List<string> listIP = new List<string>();
            foreach(string ip in IParr)
            {
                listIP.Add(ip);
            }
            listIP.Sort();//直接调用List的Sort方法进行排序

            foreach(string ip in listIP)
            {
                Console.WriteLine(Regex.Replace(ip,@"0*(\d+)","$1"));
            }

            Console.ReadKey();
        }

  

posted @ 2013-07-02 22:19  liqipeng  阅读(407)  评论(0编辑  收藏  举报