2009-03-05
在java中从字符串文本中抽取剥离出日期时间
标签:Java, 正则表达式有时候,你可能需要从一段字符串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"的日期时间。如果时间格式为缩写,还不能够处理,不过很容易可以进行扩展。
本文可以自由转载,转载时请保留全文并注明出处:
转载自仲子说 [ http://www.wangzhongyuan.com/ ]
原文链接:http://www.wangzhongyuan.com/archives/633.html