Regex Capture Groups

Formatting Dates with Regex

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved