Java 使用正则表达式提取字符串中的时间(年月日时分秒)

    public static void main(String[] args) {

        //        String str = "2015/07/20 11:01 来源: 测试";
//        String str = "[INFO][2018-04-23 10:29:08 911][http-nio-6900-exec-8]";

        String str_1 = "[INFO][2018-04-23 10:29:08 911][http-nio-6900-exec-8]";

//        String regex = "\\d{4}[-]\\d{2}[-]\\d{2} \\d{2}:\\d{2}:\\d{2} \\d{3}";
        String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} \\d{3}";

//        String regex = "\\[(\\d+.*\\s\\d{3})]";

        Pattern p = Pattern.compile(regex);
        Matcher matcher = p.matcher(str_1);
        if (matcher.find()) {
            System.out.println(matcher.groupCount());
            System.out.println(matcher.group(0));
        }
    }

输出结果:

0
2018-04-23 10:29:08 911

你可能感兴趣的:(Java基础)