Mac Mac -3 years ago 109
C++ Question

How to have regex to match middle of sentence?

I am trying to get a regex to match something on a string and then capture the rest of the string. According to https://regex101.com/ the regex below should work, but it is not. It seems like the c++ regex will match only from the start of the string. How can I get it to start from the middle of the string? I know that I can

.*?\/word(.*)
but I would rather not because the regex is a user input...

std::string uri("a/word/");
std::smatch match;
std::regex rgx(R"(\/word(.*))");
if (std::regex_match(uri, match, rgx)) {
std::cout << match[0] << ' ' << match[1];
}

Answer Source

regex_match is supposed to match the entire input sequence, not some part of it. For the latter, you need regex_search.

Using that, your example prints /word/ /.

Live demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download