第十一节:第一部分:正则表达式:应用案例、爬取信息、搜索替换

发布于:2025-05-31 ⋅ 阅读:(18) ⋅ 点赞:(0)

正则表达式介绍

正则表达式

String提供的正则表达式的方法的书写规则

匹配正则表达式的方法

正则表达式总结

正则表达式总结

正则表达式作用:

正则表达式作用

作用三:搜索替换

在这里插入图片描述

案例分析及代码(图片解析)

案例分析及代码

代码:

代码一:校验手机号和邮箱格式是否正确

package com.itheima.day15_regex;

import java.util.Scanner;

public class RegexTest3 {
    public static void main(String[] args) {
        //checkPhone();
        checkEmail();
    }

    //检查手机号
    public static void checkPhone() {
        while (true) {
            System.out.println("请您输入您的电话号码(手机|座机):");
            Scanner sc = new Scanner(System.in);
            String phone = sc.nextLine();
            //18676769999 010-3424242424 0104644535
            //  手机号         座机号         座机号
            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();
            /*dlei0009@163.com
              25143242@qq.com
              itheima@itcast.com
               itheima@itcast.cn
            */
            if (email.matches("\\w{2,}@(\\w{2,20}\\.\\w{2,10}){1,2}")){
                System.out.println("您输入的邮箱格式正确~~~");
                break;
            }else {
                System.out.println("您输入的邮箱格式不正确~~~");
            }
        }

    }

}

结果1

代码二:使用正则表达式做搜索替换,内容分割。

package com.itheima.day15_regex;

import java.util.Arrays;

//目标:掌握使用正则表达式做搜索替换,内容分割。
public class RegexTest4 {
    public static void main(String[] args) {
        //1、public String replaceAll(String regex,String newstr):按照正则表达式匹配的内容进行替换
        // 需求1:请把 古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴,中间的非中文字符替换成“-"
        String str1 ="古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
        System.out.println(str1.replaceAll("\\w+", "-"));
        //需求2(拓展):某语音系统,收到一个口吃的人说的"我我我喜欢编编编编编编编编编编编编程程程!",需要优化成"我喜欢编程!"。
        /*(.)一组:.匹配任意字符的。
         \\1:为这个组声明一个组号:1号
         +:声明必须是重复的字
         $1:可以取到第1组代表的那个重复的字
        * */
        String str2 ="我我我喜欢编编编编编编编编编编编编程程程!";
        System.out.println(str2.replaceAll("(.)\\1+","$1"));
        // 2、public string[]split(String regex):按照正则表达式匹配的内容进行分割字符串,反回一个字符串数组。
        // 需求1:请把古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴,中的人名获取出来。
        String str3 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
        String[] names =str3.split("\\w+");
        System.out.println(Arrays.toString(names));
    }
}

结果2