#include <iostream>
#include <regex>
#include <string>
//#include <sstream>
//#include <algorithm>
int main()
{
    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";
    std::regex re(R"((begin[^(]*)(\([^)]*\)))");
    std::regex rxReplace(R"(\bfoo\b)");
    std::string output_text;
    auto callback = [&](std::string const& m){
        //std::istringstream iss(m);
        std::smatch smtch;
        if (regex_search(m, smtch, re)) {
			output_text += smtch[1].str();
			output_text += std::regex_replace(smtch[2].str().c_str(), rxReplace, "abc");
        } else {
        	output_text += m;
        }
    };

    std::sregex_token_iterator
        begin(input_text.begin(), input_text.end(), re, {-1,0}),
        end;
    std::for_each(begin,end,callback);

    std::cout << output_text;
    return 0;
}