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);
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值