Using regex to format dates in C++ involves capturing the different parts of a date string and rearranging them. For example, converting a date from MM/DD/YYYY
to YYYY/MM/DD
.
Here’s how to achieve this with std::regex_replace()
:
#include <iostream>
#include <regex>
int main() {
std::string input = "12/31/2023";
std::regex pattern(
R"((\d{2})/(\d{2})/(\d{4}))"
);
std::string replacement = "$3/$1/$2";
std::string result = std::regex_replace(
input, pattern, replacement);
std::cout << "Original: " << input
<< "\nFormatted: " << result;
}
Original: 12/31/2023
Formatted: 2023/12/31
In this example, (\d{2})
captures the month and day, while (\d{4})
captures the year. The replacement string $3/$1/$2
rearranges the captured groups.
For more complex date formats, you can extend the regex pattern and replacement string. For example, converting MM-DD-YYYY
to DD.MM.YYYY
:
#include <iostream>
#include <regex>
int main() {
std::string input = "12-31-2023";
std::regex pattern(
R"((\d{2})-(\d{2})-(\d{4}))");
std::string replacement = "$2.$1.$3";
std::string result = std::regex_replace(
input, pattern, replacement);
std::cout << "Original: " << input
<< "\nFormatted: " << result;
}
Original: 12-31-2023
Formatted: 31.12.2023
C++ does not support named capture groups directly, but you can achieve similar results with careful grouping and replacements.
Regex in C++ provides a flexible way to reformat date strings. By capturing the different components of the date and rearranging them in the replacement string, you can easily convert between different date formats.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to regular expression capture groups, and how to use them in C++ with regex search
, replace
, iterator
, and token_iterator