zoukankan      html  css  js  c++  java
  • 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));
        }

    测试结果:

    重视基础,才能走的更远。
  • 相关阅读:
    Service、chkconfig命令
    mongoDB 入门
    HTTP 缓存
    MIME类型记录
    CSS3 动画 思维导图
    部署Seafile服务
    AngularJS 学习笔记
    Bootstrap3 学习笔记
    CSS 弹性盒
    传送门(portal)
  • 原文地址:https://www.cnblogs.com/xzlf/p/12689036.html
Copyright © 2011-2022 走看看