How to get date out of Java String using RegExp

By: Slav Kurochkin

In my current project I need get string " 4/27/2015 12:25:22 PM " and extract date from it, there is plenty examples how to extract dd/mm/yyyy, but it was quite difficult find a solution for mm/dd/yyyy, wait a second what if format you looking for is m/d/yyyy? Well, here is a simple solution we come up with:

 public static String getDateFromDebugger(String date){
// call getDate method
        String[] dates = getDate(date);
// convert Array into string, so we will get "[4/27/2015]"
        String str = Arrays.toString(dates);
        System.out.println(str.substring(1, str.length()-1));
// well, now we need remove extra characters "[" and "]" 
        String dateFromDebuggerString = str.substring(1, str.length()-1);
// return date
        return dateFromDebuggerString;
    }

All magic is happening here:

private static String[] getDate(String dater) {

        int count=0;
        String[] allMatches = new String[1];
// extract date using RegExp
        Matcher m = Pattern.compile("(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])/(?:[0-9]{2})?[0-9]{2}").matcher(dater);
        while (m.find()) {
            allMatches[count] = m.group();
            count++;
        }
        return allMatches;
    }

Reference[Regular Expressions Cookbook, 2nd Edition]

View Comments

Leave a Comment

Use markdown or basic HTML and be nice.