Editor

Extract Dates From Text

#336 · Regular expressions · Intermediate · 85 XP · about 18 min

Emails, invoices and chat logs mention dates in different styles. Write extract_dates(text) that finds every date written in one of these two forms:

  • YYYY-MM-DD, for example 2024-03-15
  • DD/MM/YYYY, for example 15/03/2024

Each part has exactly the number of digits shown. A piece of text with one of these shapes is a date only when both of these are true:

  • It is a real calendar date: the month is 01 to 12, and the day exists in that month. February has 29 days in a leap year and 28 otherwise.
  • It does not touch another digit: the character right before it and the character right after it (when there are any) are not digits.

A year is a leap year when it divides by 4, except years that divide by 100 but not by 400: 2000 was a leap year, 1900 was not.

Return a list of the different dates found, written as 'YYYY-MM-DD' strings, each date once, in increasing order. The same day written in both styles counts once.

Examples

extract_dates('Invoice 2024-03-15, paid 20/03/2024.')
# returns ['2024-03-15', '2024-03-20']
extract_dates('Due 31/04/2024 or 2024-02-30?')
# returns []
extract_dates('Born 29/02/2000, party on 2000-02-29 again')
# returns ['2000-02-29']

April has only 30 days and February never has 30, so the second text holds no real date.

Constraints

  • text has at most 100,000 characters, all ASCII.
  • In every date-shaped piece of text, the year's first digit is 1 to 9.
  • Two date-shaped pieces of text never overlap.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.