JAVA正则表达式练习题(IP地址排序、检验email地址)

1、需求: 将“我我我、、、我我、、我要、我要要、、、要要要、、要要、、学学学、、、、学学编、、、学编编编、、编编编程、、程程”还原成:我要学编程

public class RegexTest1 {
    public static void main(String[] args) {
        String temp = "我我我、、、我我、、我要、要要、、、要要要、、要要、、学学学、、、、学学编、、、编编编、、编编编程、、程程";
        temp=temp.replaceAll("(、+)","");
        temp=temp.replaceAll("(.)\\1+", "$1");
        System.out.print(temp);
    }
}

2、需求:对IP地址进行排序

import java.util.Arrays;
public class RegexSortIP {
    public static void main(String[] args) {
        // 对IP地址进行排序:192.168.1.200 10.10.10.10 3.3.50.3 127.0.0.1
        String temp = "192.168.1.200 10.10.10.10 3.3.50.3 127.0.0.1";       
        temp=temp.replaceAll("(\\d+)", "00$1");
        temp=temp.replaceAll("0+(\\d{3})", "$1");//将ip地址补成同样位数
        String[] str=temp.split(" +");
        Arrays.sort(str);
        for(String ips:str)
        System.out.println(ips.replaceAll("0+(\\d+)", "$1"));
}
}

输出为
3.3.50.3
10.10.10.10
127.0.0.1
192.168.1.20
3、需求:检验email地址

public class RegexTest {
    public static void main(String[] args) {
        String mail="zsy@sina.com.cn";
        String regex="\\w+@[a-zA-Z0-9]+(\\.[a-zA-Z]{2,3}){1,2}";//注意:这种匹配方式适用于国内部分邮件地址,不能匹配所有的邮件
        boolean b=mail.matches(regex);
        System.out.println(mail+" is  "+b);
    }
}

版权声明:本文为sinat_36713319原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。