正则表达式提取时间

来源:互联网 发布:tv域名不能备案 编辑:程序博客网 时间:2024/05/17 06:53

时间的各种格式都可以通过正则表达式来匹配,例如我们想精确匹配HH:mm的时间,即包含小时和分钟,可以使用下面的表达式:

^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

更多时候我们想从字符串中提取,而不是完全匹配字符串,把开头和结尾的去掉:

([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]

更多关于时间和日期的正则表达式,参考: RegExLib.

下面的Java代码提取时间:

    public static String extractTime(String pInput) {        if (pInput == null) {            return null;        }        String regEx = "([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]";        Pattern p = Pattern.compile(regEx);        Matcher matcher = p.matcher(pInput);        if (matcher.find()) {            return matcher.group();        } else {            return null;        }    }

测试:

    public static void main(String... strings) {        System.out.println(extractTime("01:57 CST (+1) (?)"));    }

输出:

01:57
0 0
原创粉丝点击