首页 > 其他 > 详细

正则表达式

时间:2021-05-29 17:25:16      阅读:19      评论:0      收藏:0      [点我收藏+]

编译正则表达式

        String re = "\d+";
        Pattern compile = Pattern.compile(re);
        Matcher matcher = compile.matcher("123123123213");

提取字符串

        // 一个括号内会被分为一个group
        String re = "(\\d{2}):(\\d{2}):(\\d{2})";
        Pattern compile = Pattern.compile(re);
        Matcher matcher = compile.matcher("24:12:64我是不匹配99:12:22");
        while (matcher.find()) {
            System.out.println("----------------");
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println(i + "\t:\t" + matcher.group(i));
            }

        }

输出

----------------
0	:	24:12:64
1	:	24
2	:	12
3	:	64
----------------
0	:	99:12:22
1	:	99
2	:	12
3	:	22

Process finished with exit code 0

matcher 与 find的区别

matcher是一次匹配整个句子,find是尝试匹配句子中的子字符串

        // matcher
        String re = "((\\d{2}):(\\d{2}):(\\d{2}))";
        Pattern compile = Pattern.compile(re);
        Matcher matcher = compile.matcher("24:12:64sjdfksjdkfj99:12:22");
        while (matcher.find()) {
            System.out.println("----------------");
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println(i + "\t:\t" + matcher.group(i));
            }

        }

        // find
        String re = "(\\d{2}):(\\d{2}):(\\d{2})";
        Pattern compile = Pattern.compile(re);
        Matcher matcher = compile.matcher("24:12:64");
        if (matcher.matches()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println(i + "\t:\t" + matcher.group(i));
            }
        }

正则表达式

原文:https://www.cnblogs.com/xiaojiluben/p/14825416.html

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