Formatting Dates with Regex

How can you use regex to format dates in C++?

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.

Example: 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.

More Complex Formatting

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

Using Named Capture Groups

C++ does not support named capture groups directly, but you can achieve similar results with careful grouping and replacements.

Summary

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.

Regex Capture Groups

An introduction to regular expression capture groups, and how to use them in C++ with regex_search, regex_replace, regex_iterator, and regex_token_iterator

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Greedy vs Lazy Quantifiers
What are the differences between greedy and lazy quantifiers in regex?
Non-Capture Groups
What are non-capture groups and when should they be used?
Regex Replace in C++
How do you replace text in a string using regex in C++?
Splitting Strings with Regex
Can regex be used to split strings in C++?
Counting Regex Matches
How can you count the number of matches found in a string using regex?
Using Backreferences in Regex
How do you use backreferences in C++ regex?
Lookahead and Lookbehind
What are lookahead and lookbehind assertions in regex?
Third-Party Regex Libraries
Are there any recommended third-party libraries for working with regex in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant