关于正则表达式的用法

public static void checkPhone(){
        while (true) {
        System.out.println("请输入你的电话号码|座机号码:");

        Scanner sc = new Scanner(System.in);
        String phone = sc.nextLine();
            
            if(phone.matches("(1[3-9]\\d{9}|0\\d{2,7}-?[1-9]\\d{4,19})")){
                System.out.println("输入格式正确");
                break;
            }else {
                System.out.println("输入格式不正确");
            }
        }
    }


    public static void checkEmail(){
        while (true) {
            System.out.println("请输入你的电话号码|座机号码:");

            Scanner sc = new Scanner(System.in);
            String email = sc.nextLine();
            /**
             * dwsccd123@qq.com
             * scwfwd234@163.com
             * qwedds123@qwer.com.cn
             */
            if(email.matches("\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2}")){
                System.out.println("输入格式正确");
                break;
            }else {
                System.out.println("输入格式不正确");
            }
        }
    }

这是验证手机号和邮箱号是否正确的方法


 //需求:从以下内容爬取,手机,邮箱,座机,400电话等信息
    public static void method1(){
        String data = " 来缅甸学java \n " +
                " 电话: 18911111111,19911111111\n" +
                " 或者联系邮箱:miandian@qq.com\n  " +
                " 座机电话011-11111111\n          " +
                " 邮箱sqwsqwd@163.com\n           " +
                " 热线电话:400-618-8977,4001239948" ;

        //1.定义爬取规则
        String regex = "(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})|(\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2})"
                + "|(400-?\\d{3,7}-?\\d{3,7})";

        //2.把正则表达式封装成一个Pattern对象
        Pattern pattern = Pattern.compile(regex);

        //3.通过pattern对象去获取查找内容的匹配器对象
        Matcher matcher = pattern.matcher(data);

        //4.定义一个循环开始爬取信息
        while (matcher.find()){
            String rs = matcher.group();
            System.out.println(rs);
        }
    }
}

 public static void main(String args[]) {

    //把非中文字符替换成"-"
    String s1 = "喜洋洋as1231234沸羊羊asd12345美羊羊oi21345灰太狼";
    System.out.println(s1.replaceAll("\\w+","-"));

    //优化成:我是你爸吧
    String s2 = "我我我我我是你你你你你你爸爸吧吧";
        /**
         * (.)一组,匹配任意字符
         * \\1.为这个组声明一个组号: 1号
         * +:声明必须是重复的字
         * $1可以去取到第1组代表的那个重复的字
         */
    System.out.println(s2.replaceAll("(.)\\1+","$1"));


    //把名字获取出来,返回一个字符串数组
    String s3 = "喜洋洋as1231234沸羊羊asd12345美羊羊oi21345灰太狼";
        String[] names = s3.split("\\w+");
        System.out.println(Arrays.toString(names));//[喜洋洋, 沸羊羊, 美羊羊, 灰太狼]
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值