Is there a better way of doing global regex substitution?

closed account (2z0kLyTq)
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");
    }
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
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.