[Java] Java通过正则表达式对一组ip地址进行排序 →→→→→进入此内容的聊天室

来自 , 2019-09-29, 写在 Java, 查看 108 次.
URL http://www.code666.cn/view/1b0114c5
  1. public static void main(String[] args) {  
  2.         String ip = "211.64.240.23,3.3.3.3,211.64.250.21,18.23.4.57,222.33.43.2";  
  3.         System.out.println("排序前:" + ip);  
  4.         // ip地址每个.之间 最少1位最高3位 ,补两位0  
  5.         ip = ip.replaceAll("(\\d+)", "00$1");  
  6.         System.out.println("补零后:" + ip);  
  7.         // 将多余的零去掉,保持.前后的数字 只保留三位  
  8.         ip = ip.replaceAll("0*(\\d{3})", "$1");  
  9.         System.out.println("去掉多余的零后:" + ip);  
  10.         String[] ipArr = ip.split(",");  
  11.         TreeSet<String> ipSet = new TreeSet<String>();  
  12.         for (String ip_str : ipArr) {  
  13.             ipSet.add(ip_str);// 放入TreeSet会自动进行排序  
  14.         }  
  15.         System.out.print("排序后:");  
  16.         for (Object ipObj : ipSet) {  
  17.             String temp = ((String) ipObj).replaceAll("0*(\\d+)", "$1");  
  18.             System.out.print(temp + "  ");  
  19.         }  
  20.     }  
  21.  
  22. //源代码片段来自云代码http://yuncode.net
  23.                        
  24.  
  25.  
  26.  

回复 "Java通过正则表达式对一组ip地址进行排序"

这儿你可以回复上面这条便签

captcha