In order to perform text transformations using regular expressions, you should perform the following:
- Include the <regex> and <string> and the namespace std::string_literals for C++14 standard user defined literals for strings:
#include <regex>
#include <string>
using namespace std::string_literals;
- Use the std::regex_replace() algorithm with a replacement string as the third argument. Consider this example: replace all words composed of exactly three characters that are either a, b, or c with three hyphens:
auto text{"abc aa bca ca bbbb"s};
auto rx = std::regex{ R"([a|b|c]{3})"s };
auto newtext = std::regex_replace(text, rx, "---"s);
- Use the std::regex_replace() algorithm with match identifiers prefixed with a $ for the third argument. For example, replace names in the "lastname, firstname" with names in the format "firstname lastname", as follows:
auto text{ "bancila, marius"s };
auto rx = std::regex{ R"((w+),s*(w+))"s };
auto newtext = std::regex_replace(text, rx, "$2 $1"s);