Using regular expressions for string replacement
If you're coming from Perl, or if you often use the command-line utility sed
, you probably think of regexes primarily as a way to modify strings--for example, "remove all substrings matching this regex," or "replace all instances of this word with another word." The C++ standard library does provide a sort of replace-by-regex functionality, under the name std::regex_replace
. It's based on the JavaScript String.prototype.replace
method, which means that it comes with its own idiosyncratic formatting mini-language.
std::regex_replace(str, rx, "replacement")
returns a std::string
constructed by searching through str
for every substring matching the regex rx
and replacing each such substring with the literal string "replacement"
. For example:
std::string s = "apples and bananas"; std::string t = std::regex_replace(s, std::regex("a"), "e"); assert(t == "epples end benenes"); std::string u = std::regex_replace(s, std::regex("[ae]"...