• 解析正则表达式(一)


    解析正则表达式(一)

    1 含义

    文本处理的神器

    2 作用

    2.1 验证文本是否符合业务格式

    如:邮箱的验证,判断用户注册时的邮箱是否符合格式,如果不合适,就不允许注册通过

    2.1 筛选字符串

    如:爬虫,如爬取b站或者百度上面的热搜排行榜信息

    3.如何用

    3.1 步骤(基本)

    3.1.1 提供需要查找的字符串content

    String content="查找的内容";
    
    • 1

    3.1.2 提供正则表达式模板字符串regStr

    String regStr="模板格式"
    //以这个模板字符串去进行匹配,如果找到了就获取并打印出来    
    
    • 1
    • 2

    3.1.3 创建正则表达式对象(使用静态的compile方法)

    Pattern pattern=Pattern.compile(regStr);
    
    • 1

    3.1.4 创建匹配器对象

    Matcher matcher=pattern.matcher(content);
    
    • 1

    3.1.5 通过matcher.find()和matcher.group(0)获取并打印符合模板字符串的字符串

    matcher.find()为循环条件,matcher.group(0)为符合条件的每一个字符串

    //本质还是用indexOf然后往下去截取,所以如果模板字符串长度大于查找字符串,那就没有查找的必要了
    while(matcher.find()){
      System.out.println("找到了"+matcher.group(0));
    }
    
    • 1
    • 2
    • 3
    • 4

    3.2 示例代码

    //获取并打印字符串中所有连续的四个数字,用方法实现
    package Work;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Test05 {
        public static void main(String[] args) {
          //1.查找的字符串
          String content="java1234djfb7890tetx7680ncuwi123";
         //2.模板字符串
         String regex="[\\d]{4}";
         //3.创建正则表达式对象
         Pattern pattern=Pattern.compile(regex);
         //4.创建匹配器对象
         Matcher matcher=pattern.matcher(content);
         //5.获取并打印符合条件的字符串
         while(matcher.find()){
             System.out.println("找到了"+matcher.group(0));
         }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    3.3 示例代码运行截图

    在这里插入图片描述

    4.String类中的matcher方法

    4.1 语法

    字符串对象.matcher(regex);
    //regex为模板字符串
    
    • 1
    • 2

    4.2 核心内容

    若原字符串符合模板字符串这个格式(位数需要一模一样),那么就返回true,返回false

    4.3 示例代码

    package Work;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Test05 {
        public static void main(String[] args) {
          String content="1234";
          String regex01="[\\d]{4}";
          String regex02="[\\d]{3}";
          System.out.println(content.matches(regex01));
          System.out.println(content.matches(regex02));
         //这个是需要匹配原来字符串和模板字符串一模一样(位数一样)才会返回true,否则返回false
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    4.4 示例代码运行截图

    在这里插入图片描述

  • 相关阅读:
    Java入门教程(4)——JDK环境变量的配置
    提高尼日利亚稻米产量 丰收节贸促会:国稻种芯百团计划行动
    C/C++字符函数和字符串函数模拟实现与详解————长度不受限制的字符串函数
    利用Doxygen生成代码文档
    在线配置生成动态排序柱状图工具上线
    基于C++和QT实现的二进制数独游戏求解
    【微信小程序】实现组件间代码共享的behaviors
    端口探测详解
    使用React和ResizeObserver实现自适应ECharts图表
    企业微信群发助手:加速信息传递,强化营销效果的新引擎
  • 原文地址:https://blog.csdn.net/SSS4362/article/details/126024757