其他分享
首页 > 其他分享> > 2022-08-12 第五组 赖哲栋 学习笔记

2022-08-12 第五组 赖哲栋 学习笔记

作者:互联网

正则表达式

  1. 限定符的作用与它相邻的最左边的一个字符起作用
  2. 如果想要ab同时被限定怎么办?----正则表达式中可以用小括号来分组,括号内的内容会作为一个整体--^(ab)*$
- 匹配中文的字符:[],匹配的是ASCII码
- 邮箱:^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$
- 国内的座机电话:^\d{3,4}-\d{8}$
- QQ号:^[1-9][0-9]{4,11}$
- 身份证号:^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$
    //split()将字符串从正则表达式匹配的地方分开
    public void test06() {
        String regex = "[-_]";
        String str = "123-4756_qweqwe-7987_465";
        String[] split = str.split(regex);
        System.out.println(Arrays.toString(split));
    }

    @Test
    public void test05() {
        String regex = "\\d";
        String str = "1111c2222d456456456f465gh987897";

        String s = str.replaceAll(regex,"@");
        System.out.println(s);
    }

    @Test
    public void test04() {
        String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        String email = "1440542956@qq.com";
        System.out.println(email.matches(regex));
    }

    
    public void test03(){
        String regex = "cat";
        String str = "cat cat dog dog cat";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);

        //统计cat在字符串中出现的次数
        int count = 0;
        while(matcher.find()){
            count++;
        }
        System.out.println("出现了" + count + "次");
    }

    //compile(String regex)将给定的正则表达式编译赋予给Pattern类
    public void test02(){
        String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        String email = "1440542956@qq.com";
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(email);
        System.out.println(matcher.matches());
    }
    
    //matcher():匹配字符串
    public void test01() {
        String str = "hello,i am from jilin changchun!";
        // 必须包含jilin
        String pattern = ".*jilina.*";
        boolean b = Pattern.matches(pattern,str);
        System.out.println("字符串中是否包含了jilin:" + b);
    }

标签:regex,12,匹配,String,--,Pattern,08,第五组,字符串
来源: https://www.cnblogs.com/laizhedong/p/16581097.html