Regex Replace in C++
How do you replace text in a string using regex in C++?
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.
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