zoukankan      html  css  js  c++  java
  • 正则表达式

    编译正则表达式

            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 + "	:	" + 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是尝试匹配句子中的子字符串

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class scratch_1 {
    
        public static void main(String[] args) {
            /**
             * 输出
             * ----------------
             * 0	:	24:12:64
             * 1	:	24:12:64
             * 2	:	24
             * 3	:	12
             * 4	:	64
             * ----------------
             * 0	:	99:12:22
             * 1	:	99:12:22
             * 2	:	99
             * 3	:	12
             * 4	:	22
             */
            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 + "	:	" + matcher.group(i));
                }
    
            }
    
            // find
            /**
             * 输出为空,因为后面有别的单词,不完全匹配
             * 如果替换输入字符串为24:12:64,输出
             * 0	:	24:12:64
             * 1	:	24
             * 2	:	12
             * 3	:	64
             */
            String re1 = "(\d{2}):(\d{2}):(\d{2})";
            Pattern compile1 = Pattern.compile(re1);
            Matcher matcher1 = compile1.matcher("24:12:64我是不匹配99:12:22");
            if (matcher1.matches()) {
                for (int i = 0; i <= matcher1.groupCount(); i++) {
                    System.out.println(i + "	:	" + matcher1.group(i));
                }
            }
        }
    }
    
  • 相关阅读:
    Mysql 5.7解压版安装
    Java Web 整合案例
    maven 创建Java web项目
    LintCode 数字三角形
    Hibernate 泛型Dao实现
    LintCode 将二叉查找树转换成双链表
    LintCode 删除链表中倒数第n个节点
    LintCode 二级制中有多少个1
    LintCode翻转二叉树
    SpringMVC 运行流程
  • 原文地址:https://www.cnblogs.com/xiaojiluben/p/14825416.html
Copyright © 2011-2022 走看看