首页 > 编程语言 > 详细

Java 中正则表达式使用

时间:2020-04-13 09:17:32      阅读:53      评论:0      收藏:0      [点我收藏+]

正则表达式基本用法:


测试代码:

@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));
    }

 

测试结果:

技术分享图片

 

Java 中正则表达式使用

原文:https://www.cnblogs.com/xzlf/p/12689036.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!