Regular Expressions

Flashcard 9 of 10

Given the following sample text containing dates in "M/D/Y" format, how can we output the text including the day of the week like "Monday Aug 8".

The first battle was on 10/8/14, followed by additional skirmishes on 11/9/14 and 11/12/14.

We can use the gsub method on the string. gsub can be called with a regex and a block, with each match being yielded to the block where you can run arbitrary Ruby code on the match text to transform as needed.

require "date"

sample = <<-SAMPLE
The first battle was on 10/8/14,
followed by additional skirmishes
on 11/9/14 and 11/12/14.
SAMPLE

date_pattern = %r{\d+/\d+/\d+}

sample.gsub(date_pattern) do |date|
  Date.
    strptime(date, "%m/%d/%y").
    strftime("%A %b %-d")
end

The block first parses the date string, explicitly specifying the date format using strptime, then uses strftime to output the date in the preferred format.

This produces:

The first battle was on Wednesday Oct 8, followed by additional skirmishes on Sunday Nov 9 and Wednesday Nov 12.

Check out the Weekly Iteration episode on Regex, specifically the [section on using gsub with regex and a block][] for a more detailed summary.

Note: If you want to get really fancy, you can use the ActiveSupport date.day.ordinalize method to get dates like 2nd and 4th. Check out our [Weekly Iteration episode on ActiveSupport][] for more on ActiveSupport.

[Weekly Iteration episode on ActiveSupport]: https://upcase.com/videos/active-support [section on using gsub with regex and a block]: https://upcase.com/videos/regular-expressions#gsub-with-a-block

Return to Flashcard Results