一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java中正则表达式提取字符串中日期实现代码

时间:2012-08-16 编辑:简简单单 来源:一聚教程网

你可能需要从一段字符串String或者文本中抽取出或者说是过滤出日期或者时间,可以使用如下程序:

 代码如下 复制代码

public String run(String text) {
        String dateStr = text.replaceAll("r?n", " ");
        dateStr = dateStr.replaceAll("\s+", " ");       
       
        try {
           
            List matches = null;
            Pattern p = Pattern.compile("(\d{1,4}[-|\\/]\d{1,2}[-|\\/]\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})", Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
            Matcher matcher = p.matcher(dateStr);
            if (matcher.find() && matcher.groupCount() >= 1) {
                matches = new ArrayList();
                for (int i = 1; i <= matcher.groupCount(); i++) {
                    String temp = matcher.group(i);
                    matches.add(temp);
                }
            } else {
                matches = Collections.EMPTY_LIST;
            }           
           
            if (matches.size() > 0) {
                return ((String) matches.get(0)).trim();
            } else {
                return "";
            }
           
        } catch (Exception e) {
            return "";
        }
    }

这段程序目前的功能是从字符串中抽取出形式为"yyyy-MM-dd HH:mm:ss"或者是"yyyy/MM/dd HH:mm:ss"的日期时间。如果时间格式为缩写,还不能够处理,不过很容易可以进行扩展。

 

热门栏目