I'm trying to replace all occurrences of names within a given string. I'm using regex, since a simple substring match won't work in this case and I need to match full words.
My problem is that I can only match words before and after blanks. But for example I cannot replace a string when it's followed by a blank, like:
toReplace()
with: theReplacement()
My regex replace method looks like this:
void replaceWord(std::string &str, const std::string& search, const std::string& replace)
{
// Regular expression to match words beginning with 'search'
// std::regex e ("(\\b("+search+"))([^,. ]*)");
// std::regex e ("(\\b("+search+"))\\b)");
std::regex e("(\\b("+search+"))([^,.()<>{} ]*)");
str = std::regex_replace(str,e,replace) ;
}
How should the regex look like in order to ignore leading and trailing non-alphanumericals?
You need to
std::regex_replace(search, std::regex(R"([.^$|{}()[\]*+?/\\])"), std::string(R"(\$&)"))
std::regex_replace(replace, std::regex("[$]"), std::string("$$$$"))
(that is in case you replace with literal$1
text,$
can be set with$$
, so to replace with a double$
, we need$$$$
in the replacement here)"(\\W|^)("+search+")(?!\\w)
$1
at the start of the replacement pattern to keep the whitespace (if it is matched and captured into the first group with the(\W|^)
pattern).See C++ sample code:
Then,