fork download
  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. using namespace std;
  5.  
  6. std::string replaceWord(std::string &str, std::string& search, std::string& replace)
  7. {
  8. // Escape the literal regex pattern
  9. search = std::regex_replace(search, std::regex(R"([.^$|{}()[\]*+?/\\])"), std::string(R"(\$&)"));
  10. // Escape the literal replacement pattern
  11. replace = std::regex_replace(replace, std::regex("[$]"), std::string("$$$$"));
  12. std::regex e("(\\W|^)("+search+")(?!\\w)");
  13. return std::regex_replace(str, e, std::string("$1") + replace);
  14. }
  15.  
  16. int main() {
  17. std::string text("String toReplace()");
  18. std::string s("toReplace()");
  19. std::string r("theReplacement()");
  20. std::cout << replaceWord(text, s, r);
  21. return 0;
  22. }
Success #stdin #stdout 0s 4500KB
stdin
Standard input is empty
stdout
String theReplacement()