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

1. 字符串的匹配功能

2. 字符串的切割功能

3. 字符串的替换功能

4. 字符串的获取功能
匹配功能 String的matches方法

    public static void main(String[] args) {
        // 匹配手机号码是否正确
        String phone = "13222221111";
        String regex = "1[345789]\\d{9}";
        boolean matches = phone.matches(regex);
    }
切割功能 String的split(String regex)根据给定的正则拆分字符串

    public static void main(String[] args) {
        // 分割手机号的每一位数字
        String phone = "13222221111";
        String regex = "";
        String[] split = phone.split(regex);
        System.out.println(Arrays.toString(split));
    }
    结果: [1, 3, 2, 2, 2, 2, 2, 1, 1, 1, 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 you 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());
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值