加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:11:26 所属栏目:百科 来源:网络整理
导读:1. 字符串的匹配功能2. 字符串的切割功能3. 字符串的替换功能4. 字符串的获取功能 匹配功能 String的matches方法 public static void main(String[] args) { // 匹配手机号码是否正确 String phone = "15228119181"; String regex = "1[345789]d{9}"; bool
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,8,1,9,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读