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(); }
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)