java – How to parse a date from a URL format? – Education Career Blog

My database contains URLs stored as text fields and each URL contains a representation of the date of a report, which is missing from the report itself.

So I need to parse the date from the URL field to a String representation such as:


What’s the best way to extract the dates?

Some are in this format:

Note the inconsistent use of th following the day of the month in cases such as these two:

Others are in this format (with three hyphens before the date starts, no year at the end and an optional use of invoices- before report):


You want a regex like this:


This exploits that everything up through the /year/month/ part of the URL is always the same, and that no number follows till the day of the month. After you have that, you don’t care about anything else.

The first capture group is the year, the second the month, and the third the day. The day might not have a leading zero; convert from string to integer and format as needed, or just grab the string length and, if it’s not two, then concatenate it to the string “0”.

As an example:

import java.util.regex.*;

class URLDate {
  public static void
  main(String args) {
    String text = "";
    String regex = "\\d{4})/(\\d{2})/\\D+(\\d{1,2})";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);
    if (m.find()) {
      int count = m.groupCount();
      System.out.format("matched with groups:\n", count);
      for (int i = 0; i <= count; ++i) {
          String group =;
          System.out.format("\t%d: %s\n", i, group);
    } else {
      System.out.println("failed to match!");

gives the output:

matched with groups:
    1: 2010
    2: 09
    3: 1

(Note that to use Matcher.matches() instead of Matcher.find(), you would have to make the pattern eat the entire input string by appending .*$ to the pattern.)

Leave a Comment