【JAVA学习】正则表达式学习记录(1)

版权声明:转载请注明 https://blog.csdn.net/qq_33591903/article/details/83757194

                                         正则表达式学习记录(1)

有一次在面试的过程中,被问到了正则表达式,这一下触碰到了我的知识盲区了,虽然我目前还没怎么用到过正则,不过还是先学习一番吧。

package day1105;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExp1 {
    /**
     * 匹配QQ号
     * 长度为5~10位,纯数字,第一位不能为0
     */
    public static boolean isQQ(String qq) {
        //[1-9] 第一位是1~9的数字
        //[0-9]{4,9} 第二位是0~9的数字,还需要4到9位,加上第1位,满足5~10位的要求
        String regex = "[1-9][0-9]{4,9}";
        return qq.matches(regex);
    }

    /**
     * 匹配手机号
     * 长度为11位,第一位只能是1,第二位可以是3,7,8,纯数字
     */
    public static boolean isPhone(String phone) {
        //1 第一位只能是1,由于只有一个数字,就不用写[]了
        //378   第二位只能是3或7或8
        //[0-9]{9} 第三位是0~9的数字,这样的数字需要9个,加上前面的2个,满足一共1位的要求
        String regex = "1[378][0-9]{9}";
        String regex2 = "1[378]\\d{9}";
        return phone.matches(regex2);
    }

    /**
     * 使用.来切割字符串
     */
    public static String[] removeDot(String str) {
        //注意转义,而非直接使用.,否则.会匹配任何字符
        String regex = "\\.";
        return str.split(regex);
    }

    /**
     * 去掉 你你你好好啊啊啊啊 中的叠词,形成 你好啊
     */
    public static String solveRepeat(String str) {
        //  ()来表示组
        //  (.)来表示任意字符,而\\1是对组(.)中的字符进行复用,合起来就是:两个相同的字符
        //  而叠词不止是两个字的叠词,也有三个字、四个字,因此用(.)\\1+表示叠词
        //  使用$1来复用组中第1组的值(即叠词的字符),将叠词替换成叠词中第一个字符
        String regex = "(.)\\1+";
        return str.replaceAll(regex, "$1");

    }

    /**
     * 获取一个文件内所有的邮箱号
     */
    public static void getEmail() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(new File("g:\\test.html")));
            String regex = "[1-9]{5,10}@qq.com";
            Pattern p = Pattern.compile(regex);
            String line = "";
            while ((line = br.readLine()) != null) {
                Matcher m = p.matcher(line);
                while (m.find()) {
                    System.out.println(m.group());
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println(isQQ("767638734"));
        System.out.println(isPhone("18806210604"));
        String temp = "qw.we.rt.ty.yu";
        String[] strArr = removeDot(temp);
        for (String s : strArr) {
            System.out.println(s);
        }
        System.out.println(solveRepeat("你你你好好啊啊啊啊"));
        getEmail();

    }
}

猜你喜欢

转载自blog.csdn.net/qq_33591903/article/details/83757194