Home  >  Article  >  Backend Development  >  Teach you how to use regular expressions to sort IPs

Teach you how to use regular expressions to sort IPs

小云云
小云云Original
2017-12-05 14:28:111381browse

正则表达式在我们开发中必不可少,本文我们主要介绍了利用正则表达对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

以上内容就是利用正则表达对IP进行排序的实现代码,希望能帮助到大家。

相关推荐:

php正则表达式应用

python编译正则表达式提高效率方法详解

Python中正则表达式的知识汇总分享

The above is the detailed content of Teach you how to use regular expressions to sort IPs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn