正则表达式的常见功能(作用)


1. 字符串的匹配功能

2. 字符串的切割功能

3. 字符串的替换功能

4. 字符串的获取功能

匹配功能 String的matches方法

    public static void main(String[] args) {
        // 匹配手机号码是否正确
        String phone = "15228119181";
        String regex = "1[345789]\\d{9}";
        boolean matches = phone.matches(regex);
    }

切割功能 String的split(String regex)根据给定的正则拆分字符串

    public static void main(String[] args) {
        // 分割手机号的每一位数字
        String phone = "15228119181";
        String regex = "";
        String[] split = phone.split(regex);
        System.out.println(Arrays.toString(split));
    }
    结果: [1, 5, 2, 2, 8, 1, 1, 9, 1, 8, 1]


    public static void main(String[] args) {
        // 切割获取每一个单词(去除空格)
        String phone = "are      you  ok !";
        String regex = "\\p{Space}+";
        String[] split = phone.split(regex);
        System.out.println(Arrays.toString(split));
    }
    结果: [are, you, ok, !]


    这里有一个对split方法理解不正确的用法,要注意:
    public static void main(String[] args) {
        // 切割获取每一个单词(去除.)
        String phone = "are.you.ok !";
        //split方法传入的是正则,所以传入参数应该为 \\. 用来转义.符号
        String regex = ".";
        String[] split = phone.split(regex);
        //这样切割出来什么都没有
        System.out.println(Arrays.toString(split));
    }
    结果: []

替换功能  String类的replaceAll(String regex,String replacement)

    将.替换成空格
    public static void main(String[] args) {
        String english = "are.you.ok !";
        String regex = "\\.";
        String s = english.replaceAll(regex, " ");
        System.out.println(s);
    }
    结果: are yuo ok !

    将中间的0替换成*
    public static void main(String[] args) {
        String phone = "15800001111";
        String s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        System.out.println(s);
    }
    结果: 158****1111

获取功能 

    public static void main(String[] args) {
        // 获取3个字母组成的单词
        // 将正则封装成对象
        Pattern p = Pattern.compile("\\b[a-z]{3}\\b");
        // 指定要匹配的字符串
        Matcher m = p.matcher("da jia hao ming tian bu fang jia!");
        // 获取匹配的数据
        while (m.find()) {
            System.out.println(m.group());
        }
    }

来源:https://blog.csdn.net/chuxin_mm/article/details/85157570

猜你喜欢

转载自www.cnblogs.com/thatme/p/10192961.html