C++ regex string literal with capturing group

ont*_*cks 3 c++ regex

I have a std::string containing backslashes, double quotes. I want to extract a substring using capture group, but I am not able to get the syntax right. e.g.

std::string str(R"(some\"string"name":"john"\"lastname":"doe")");  //==> want to extract "john"
std::regex re(R"(some\"string"name":")"(.*)R"("\"lastname":"doe")");    //==> wrong syntax

std::smatch match;
std::string name;
if (std::regex_search(str, match, re) && match.size() > 1)
{
    name = match.str(1);
}
Run Code Online (Sandbox Code Playgroud)

rus*_*tyx 5

  1. 使用不在字符串中出现的分隔符。例如R"~( .... )~"

  2. 您仍然需要转义\for 正则表达式。要匹配\字面意思,请使用\\.

  3. 您可能希望在找到最短的匹配项后立即停止。所以使用(.*?)

    std::regex re(R"~(some\\"string"name":"(.*?)"\\"lastname":"doe")~");
    
    Run Code Online (Sandbox Code Playgroud)

  • `R"..."` 是新的文字字符串语法。没有它“\\”将需要变成“\\\\”:( (2认同)