31. Transforming dates in strings

Text transformation can be performed with regular expressions using std::regex_replace(). A regular expression that can match dates with the specified formats is (\d{1,2})(\.|-|/)(\d{1,2})(\.|-|/)(\d{4}). This regex defines five capture groups; the 1st is for the day, the 2nd is for the separator (. or -), the 3rd is for the month, the 4th is again for the separator (. or -), and the 5th is for the year.

Since we want to transform dates from the format dd.mm.yyyy or dd-mm-yyyy to yyyy-mm-dd, the regex replacement format string for std::regex_replace() should be "($5-$3-$1)":

std::string transform_date(std::string_view text){   auto rx = std::regex{ R"((\d{1,2})(\.|-|/)(\d{1,2})(\.|-|/)(\d{4}))" }; return std::regex_replace(text.data(), ...

Get The Modern C++ Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.