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.
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
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.
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
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.
An introduction to regular expression capture groups, and how to use them in C++ with regex search
, replace
, iterator
, and token_iterator