Java学习-14 算法-02

正则表达式

就是由一些特定的字符组成,代表是一个规则

校验格式正确

校验内容

Pattern、Matcher

public class Test4 {
    public static void main(String[] args) {
        method1();
    }

    public static void method1() {
        String data = " 来黑马程序员学习Java,\n" +
                "电话: 1866668888,18699997777\n" +
                "或者联系邮箱: boniu@itcast.cn,n" +
                "市机电话: 01036517895,810-98951256\n" +
                "邮箱: bozai@itcast.cn,\n" +
                "邮箱: dlei0009@163.com,n" +
                "邮箱: dlei.0009@163.com,n" +
                "热线电话: 400-618-9090 ,400-618-4000,4006184000,4006189090";
        // 手机 电话 邮箱 400
        String regex = "([1][3-9]\\d{9})|(0\\d{2,7}-?\\d{4,19})|((\\w|[.]){2,}@\\w{2,20}(\\.\\w{2,10}){1,2})" +
                "|(400-?\\d{3,7}-?\\d{3,7})";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(data);
        while (matcher.find()){
            String rs = matcher.group();
            System.out.println(rs);
        }
    }
}

用于搜索替换、分割内容

replaceAll、split 以及   \\组号 $组号调用

public class Test5 {
    public static void main(String[] args) {
        // 1、public String replaceAll(String regex ,String newStr): 按照正则表达式区配的内容进行替换
        // 需求1:请把 古力娜扎8888迪丽热巴999aa5566马尔扎fbbfsfs42425卡尔扎巴,中网的非中文字符营换成"-"
        String data1 = "古力娜扎8888迪丽热巴999aa5566马尔扎fbbfsfs42425卡尔扎巴";
        System.out.println(data1.replaceAll("\\w+", "-"));

        // 需求2(拓展):某语音系统,收到一个口吃的人说的“我我我喜欢编编编编编编编编编编编编程程程! ",需要优化成"我喜欢编程!"。
        String data0 = "我我我喜欢编编编编编编编编编编编编程程程!";
        // (.)一组:.匹配任意字符的。*
        // \\1 :为这个组声明一个组号:1号
        // +: 声明各须是重复的字
        // $1可以去到第1组代表的服个重复的字
        System.out.println(data0.replaceAll("(.)\\1+", "$1"));

        // 2、public String[] spit(String regex):按照正则表达式区配的内容进行分字符,反同一个字符串数组
        // 需求1:请把 古力娜扎i8888迪热巴9995566马尔扎哈fbbfsfs42425卡尔扎巴,中的人名获取出来
        String data2 = "古力娜扎i8888迪热巴9995566马尔扎哈fbbfsfs42425卡尔扎巴";
        String[] res = data2.split("\\w+");
        System.out.println(Arrays.toString(res));
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值