C++ Regex always matching entire string

Viewed 30

Whenever I use a regex function it matches the entire string for some reason.

#include <iostream>
#include <regex>

int main() {
    std::string text = "This (is a) test";
    std::regex pattern("\(.+\)");
    std::cout << std::regex_replace(text, pattern, "isnt") << std::endl;
    return 0;
}

Output: isnt

1 Answers

Your pattern unfortunately is not what it seems to be. Here is the problem. Imagine for some reason you want to match tabs in with you regex. You might try this.

std::regex my_regex("\t");

This would work, but the string your std::regex class has seen is " ", not "\t". This is because of how C++ threats escaped characters. To pass literal "\t", you had to do the following.

std::regex my_regex("\\t");

So the correct syntax for your regex is.

std::regex pattern("\\(.+\\)");
Related