Is there a better way of doing global regex substitution?
Dec 30, 2019 at 8:09pm UTC
This is what I'm use to writing
s/\bS.*?\b/wilson/g;
And this is what I have working, but it seems wrong. Is there a better way of doing it?
1 2 3 4 5
std::regex r(R"(\bS.*?\b)" );
while (std::regex_search(str, r)) {
str = std::regex_replace(str, r, "wilson" );
}
Dec 30, 2019 at 11:32pm UTC
1 2 3 4 5 6 7 8 9
#include <regex>
#include <iostream>
#include <string>
int main()
{
for (std::string line; std::getline(std::cin, line); )
std::cout << std::regex_replace(line, std::regex{R"(\bS.*?\b)" }, "Wilson" ) << '\n' ;
}
Last edited on Dec 30, 2019 at 11:33pm UTC
Dec 30, 2019 at 11:35pm UTC
regex_replace does a "global" replace within the string by default.
If you want to replace only the first match, you need to include the following as a fourth parameter:
std::regex_constants::format_first_only
Topic archived. No new replies allowed.