Detailed explanation of sorting IP using regular expressions

零下一度
Release: 2023-03-14 07:30:02
Original
1446 people have browsed it

直接 排序会出现问题了,是按照字符串字典顺序排的序。
问题在哪呢?是因为每一个地址段的位数不对。下面就是介绍用正则表达对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]);
 }
 }
}
Copy after login

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
Copy after login

The above is the detailed content of Detailed explanation of sorting IP using regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template