I've found this topic which only explains how to replace the first regex match. What about some n'th match?
Say I have a string and a regex like these:
std::string str = "fast cast dust crust must last rust";
std::regex expr = " .(a|u)st";
How can I replace, say, the third match with some other sequence? std::regex_replace allows to replace either all matches or the first one. I'm also thinking about std::regex_iterator, but still can't figure out how to apply it in this task. What are the most convenient ways to solve the problem?
I've managed to come up with my own solution. I use
std::string::replacetaking a pair of iterators in the firststd::sub_matchfrom the advancedstd::sregex_iterator:One could add some extra iterator validations if they wish. I'll keep it brief.
The output is:
It's worth mentioning, however, that
std::regex_replacereturns a modified copy whereas the solution above changes the string in place. Also, one should be careful as the iterators in thesub_matches may become invalidated once the replacement has been completed.