Regex Capture Groups

Regex Replace in C++

How do you replace text in a string using regex in C++?

Abstract art representing computer programming

In C++, you can replace text in a string using the std::regex_replace() function from the <regex> library. This function allows you to search for patterns in a string and replace them with new text.

Basic Replacement

To perform a basic replacement, you need a string, a regex pattern, and a replacement string:

#include <iostream>
#include <regex>

int main() {
  std::string input = "Hello World";
  std::regex pattern("World");
  std::string replacement = "Everyone";

  std::string result = std::regex_replace(
    input, pattern, replacement);
  std::cout << "Before: " << input <<
    "\nAfter: " << result;
}
Before: Hello World
After: Hello Everyone

Replacement with Capture Groups

You can also use capture groups in your regex pattern and refer to them in the replacement string using $ followed by the group number:

#include <iostream>
#include <regex>

int main() {
  std::string input = "abc123def456";
  std::regex pattern("(\\d+)");
  std::string replacement = "[$1]";

  std::string result = std::regex_replace(
    input, pattern, replacement);
  std::cout << "Before: " << input
    << "\nAfter: " << result;
}
Before: abc123def456
After: abc[123]def[456]

Here, (\d+) captures one or more digits, and [$1] replaces each match with the captured digits enclosed in brackets.

Escaping Special Characters

If your replacement string includes special characters, you need to escape them with a backslash. For example, to include a literal dollar sign in the replacement:

#include <iostream>
#include <regex>

int main() {
  std::string input = "Price: 5 dollars";
  std::regex pattern("(\\d+) dollars");
  std::string replacement = "$$ $1";

  std::string result = std::regex_replace(
    input, pattern, replacement);
  std::cout << "Before: " << input
    << "\nAfter: " << result;
}
Before: Price: 5 dollars
After: Price: $ 5

Summary

Using std::regex_replace() in C++ allows you to perform complex string replacements efficiently. Whether you need simple text replacements or advanced modifications using capture groups, std::regex_replace() provides a powerful tool for manipulating strings.

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