Extract valid dates from a text
Coding problemMediumAsked in: Capgemini, Infosys
Given a text, find every date written as DD-MM-YYYY: two digits for the day, a hyphen, two digits for the month, a hyphen and four digits for the year. Return the dates in the order they appear, written exactly as in the text.
A match counts only when:
- the character just before it and the character just after it (when there is one) are not digits, so
"123-04-2024"holds no date; - it is a real calendar date: month 01 to 12, year 0001 to 9999, and a day that exists in that month. February has 29 days in leap years (divisible by 4, except years divisible by 100 that are not divisible by 400) and 28 otherwise.
Examples
Example 1
Input: text = "Released on 15-08-2024, patched on 01-01-2025."
Output: ["15-08-2024","01-01-2025"]
Example 2
Input: text = "Due 31-04-2024 or 30-04-2024"
Output: ["30-04-2024"]
April has only 30 days.
Example 3
Input: text = "Order 129-02-2024 and 29-02-2023"
Output: []
The first has a digit before it; 2023 is not a leap year.
Constraints
- The length of text is between 0 and 100,000
- text holds printable ASCII characters only
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.