package IPSort;
import java.util.Arrays;
/**
* 利用正则表达对IP进行排序,分四步
* @author tiger
*
*/
public class IPSortTest {
public static void main(String[] args) {
String[] ips = {"10.2.4.23","192.168.1.2","173.68.46.65","191.158.6.2","9.2.4.23"};
System.out.println("------1、补零------");
for (int i = 0; i ips.length; i++) {
ips[i] = ips[i].replaceAll("(\\d+)", "00$1");
System.out.println(ips[i]);
}
System.out.println("------2、截取------");
for (int i = 0; i ips.length; i++) {
ips[i] = ips[i].replaceAll("0*(\\d{3})", "$1");
System.out.println(ips[i]);
}
System.out.println("------3、排序------");
Arrays.sort(ips);
for (int i = 0; i ips.length; i++) {
System.out.println(ips[i]);
}
System.out.println("------4、去零------");
for (int i = 0; i ips.length; i++) {
ips[i] = ips[i].replaceAll("0*(\\d+)", "$1");
System.out.println(ips[i]);
}
}
}
------原IP地址------
10.2.4.23
192.168.1.2
173.68.46.65
191.158.6.2
9.2.4.23
------1、加零,按字符串顺序比较------
0010.002.004.0023
00192.00168.001.002
00173.0068.0046.0065
00191.00158.006.002
009.002.004.0023
------2、截取,保留三位------
010.002.004.023
192.168.001.002
173.068.046.065
191.158.006.002
009.002.004.023
------3、排序------
009.002.004.023
010.002.004.023
173.068.046.065
191.158.006.002
192.168.001.002
------4、去零------
9.2.4.23
10.2.4.23
173.68.46.65
191.158.6.2
192.168.1.2
以上所述是小编给大家介绍的利用正则表达对IP进行排序的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!