Home >Web Front-end >JS Tutorial >How to sort IPs using regular expressions
这次给大家带来正则表达式怎样对IP进行排序,正则表达式对IP进行排序的注意事项有哪些,下面就是实战案例,一起来看一下。
1、补零,使得可以按照字符串顺序进行比较。
2、截取保留后三位(ip地址最多就3位)。
3、利用Arrays.sort()方法对截取的字符串进行排序。。
4、去除多余的0,回复ip原样。
5、实现代码:
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]); } } }
6、运行结果:
------原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
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to sort IPs using regular expressions. For more information, please follow other related articles on the PHP Chinese website!