• 正则表达式


    正则表示:

    • 正则表达式可以用一些规定的字符来制定规则,并用来校验数据格式的合法性。

    正则表达式的匹配规则:

    如果不记得,可以去API文档搜索Pattern正则表达式

    字符串对象提供了匹配正则表达式规则的API:

    public boolean matches(String regex)
    //判断是否匹配正则表达式,匹配返回true,不匹配返回false。
    
    • 1
    • 2

    正则表达式在字符串方法中的使用:

    方法名说明
    public String replaceAll(String regex,String newStr)按照正则表达式匹配的内容进行替换
    public String[] split(String regex)按照正则表达式匹配的内容进行分割字符串,返回一个字符串数组
    String names = "孙悟空fiowhg23435猪八戒fjoiw234352白龙马";
    String[] s = names.split("\\w+");
    for(int i=0;i<s.length;i++){
        System.out.println(s[i]);
        /*
        输出:
        孙悟空
        猪八戒
        白龙马
        */
    }
    
    String name2 = names.replaceAll("\\w+","  "); //用两个空格代替要替换的内容,组成新的字符串
    System.out.println(name2); //孙悟空  猪八戒  白龙马
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    正则表达式爬取信息:

    package com.lipn.regulardemo;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Crawling {
        public static void main(String[] args) {
            String rs = "来黑马程序员学习Java,联系邮箱itheima@itcast.cn,电话18762832633,0203232323," +
                    "邮箱bozai@itcast.cn,400-100-3232,4001003232";
    
            /*
            需求:
            从上面的内容中爬取出电话号码和邮箱。
             */
    
            //1.定义爬取规则,字符串形式
            String regex = "1[3-9]\\d{9}|\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}|" +
                    "400-?\\d{3,9}-?\\d{3,9}";
    
            //2.把这个爬取规则编译成匹配对象
            Pattern pattern = Pattern.compile(regex);
    
            //3.得到一个内容匹配器对象
            Matcher matcher = pattern.matcher(rs);
    
            //4.开始找了
            while(matcher.find()){
                String rs1 = matcher.group();
                System.out.println(rs1);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
  • 相关阅读:
    百度相关词易语言查询代码
    SpringMVC执行流程
    win10 + VS2015 + libtorch 环境搭建
    jar服务导致cpu飙升问题-带解决方法
    扩展点系列之SmartInstantiationAwareBeanPostProcessor确定执行哪一个构造方法 - 第432篇
    chatgpt fine-tuning 官方文档
    Linux | Linux权限详解
    调试工具记录
    顶刊BMJ杂志推荐方法学文章!断点回归方法介绍
    6.filters滤波
  • 原文地址:https://blog.csdn.net/Lipn_/article/details/132635673