fork(3) download
  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. //#include <sstream>
  5. //#include <algorithm>
  6. int main()
  7. {
  8. std::string input_text = "my text\nbegin foo even 14 spaces and maybe \nnew line(\nsome text only replace foo foo bar foo, keep the rest\n)\nsome more text not replace foo here";
  9. std::regex re(R"((begin[^(]*)(\([^)]*\)))");
  10. std::regex rxReplace(R"(\bfoo\b)");
  11. std::string output_text;
  12. auto callback = [&](std::string const& m){
  13. //std::istringstream iss(m);
  14. std::smatch smtch;
  15. if (regex_search(m, smtch, re)) {
  16. output_text += smtch[1].str();
  17. output_text += std::regex_replace(smtch[2].str().c_str(), rxReplace, "abc");
  18. } else {
  19. output_text += m;
  20. }
  21. };
  22.  
  23. std::sregex_token_iterator
  24. begin(input_text.begin(), input_text.end(), re, {-1,0}),
  25. end;
  26. std::for_each(begin,end,callback);
  27.  
  28. std::cout << output_text;
  29. return 0;
  30. }
Success #stdin #stdout 0s 3564KB
stdin
Standard input is empty
stdout
my text
begin foo even 14 spaces and maybe 
new line(
some text only replace abc abc bar abc, keep the rest
)
some more text not replace foo here