Search code examples
c++regexiteratorifstreamofstream

parse inFile line by line while using regex to execute function


I sort of painted myself in a corner and need some guidance. I'm doing some parsing using regex while reading from an infstream. What I want to do is

while(getLine(inFile, str)) {

     search(str) for regex match
     if(match)
         str = my_function(str)
         outFile << str
     else 
         outFile unchanged str
}

As it stands, I'm doing this:

while(getLine(inFile, str)) {

 auto des = std::sregex_iterator(str.cbegin(), str.cend(), dest);
 auto reg_it = std::sregex_iterator();

 std::for_each(des , reg_it, [](std::smatch const& m){
          str = my_function(str)
          outFile << str
        });
}

Unfortunately, this doesn't let me edit the file and write it back out in order, as the way I'm doing it only gives me access to the returned matches.

Any guidance would be greatly appreciated!


Solution

  • This works:

    if (std::regex_match(str.cbegin(), str.cend(), matches , my_regex)) {
            string baz;
            baz = my_function(str); // we have a match
            outFile baz;
    }
    else outFile << str << std::endl;