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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Filename: Test.java <br>
 * 
 * Description: java中正则表达式提取字符串中日期实现代码 <br>
 * 
 * @author: oschina <br>
 * @version: 1.0 <br>
 * @Createtime: Jan 21, 2013 <br>
 * 
 * @Copyright: Copyright (c)2013 by oschina <br>
 * 
 */

public class Test {

	/**
	 * @param args
	 * @author: oschina
	 * @Createtime: Jan 21, 2013
	 */
	public static void main(String[] args) {
		String str = "户号:0468773993 户名:李xx  时间:2013-1-20 15:00:00 剩余金额不足,已超过警戒点B,请速续费.";
		str = run(str);
		System.out.print(str);
	}

	/**
	 *  java中正则表达式提取字符串中日期实现代码
	 * @param text 待提取的字符串
	 * @return 返回日期
	 * @author: oschina
	 * @Createtime: Jan 21, 2013
	 */
	@SuppressWarnings("unchecked")
	public static String run(String text) { 
        String dateStr = text.replaceAll("r?n", " ");
        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 ""; 
        } 
    }
}

你可能感兴趣的:(java中正则表达式提取字符串中日期实现代码)