Java 中正则表达式使用

正则表达式基本用法:


测试代码:

@Test
    public void test01() {
        String str = "adsfd##4324";
        // 创建正则表达式对象
        Pattern p = Pattern.compile("\\w+");
        // 创建Matcher 对象
        Matcher m = p.matcher(str);
        boolean flag = m.matches();
        System.out.println(flag);

    }

 

测试结果:

 

 

正则表达式find() group():

测试代码:

@Test
    public void test02() {
        String str = "adsfd123##fdsf4324";
        // 创建正则表达式对象
        Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
        // 创建Matcher 对象
        Matcher m = p.matcher(str);
        //find() 扫描输入的序列,查找与该模式匹配的下一个子序列
        while (m.find()) {
            // group(),group(0)匹配整个表达式的子字符串
            System.out.println(m.group());
            System.out.println(m.group(0));
            // group(1),group(2)匹配对应分组
            System.out.println(m.group(1));
            System.out.println(m.group(2));
            System.out.println("=============");
        }
    }

 

测试结果:

 

 

正则表达式对象的替换操作:

测试代码:

@Test
    public void test03() {
        String str = "adsfd123##fdsf4324";
        // 创建正则表达式对象
        Pattern p = Pattern.compile("\\d");
        // 创建Matcher 对象
        Matcher m = p.matcher(str);
        // 替换(把数字替换成*)
        String newStr = m.replaceAll("*");
        System.out.println(newStr);
    }

 

测试结果:

 

 

正则表达式对象的分割字符串操作:

测试代码:

@Test
    public void test04() {
        String str = "adsfd123##fdsf4324";
        // 分割(以数字分割)
        String[] arr = str.split("\\d+");
        System.out.println(Arrays.toString(arr));
    }

 

测试结果:

 

posted @ 2020-04-13 01:32  行者老夫  阅读(364)  评论(0编辑  收藏  举报