puelo
puelo

Reputation: 5977

Why does this regex throw an exception?

I am trying to use std::regex_replace in C++11 (Visual Studio 2013) but the regex i am trying to create is throwing an exception:

Microsoft C++ exception: std::regex_error at memory location 0x0030ED34

Why is this the case? This is my definition:

std::string regexStr = R"(\([A - Za - z] | [0 - 9])[0 - 9]{2})";

std::regex rg(regexStr); <-- This is where the exception thrown

line = std::regex_replace(line, rg, this->protyp->getUTF8Character("$&"));

What i want to do: Find all matches inside a string which are of the following format:

"\X99" OR "\999" where X = A-Z or a-z and 9 = 0-9.

I also tried to use the boost regex library, but it also throws an exeception.

(Another question: Can i use the backreference as i am doing in the last line? I want to replace dynamically according to the match)

Thanks for any help

Upvotes: 1

Views: 1949

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

As per the above comments, you need to fix your regex: to match a literal backslash you need to use "\\\\" (or R("\\")).

My code that shows all the first captured groups:

string line = "\\X99 \\999";
string regexStr = "(\\\\([A-Za-z]|[0-9])[0-9]{2})";
regex rg(regexStr); //<-- This is where the exception was thrown before
smatch sm;
while (regex_search(line, sm, rg)) {
        std::cout << sm[1] << std::endl;
        line = sm.suffix().str();
    }

Output:

\X99
\999

Regarding using a method call inside a replacement string, I do not find such a functionality in the regex_replace documentation:

fmt - the regex replacement format string, exact syntax depends on the value of flags

Upvotes: 1

Related Questions