简体   繁体   中英

C++ regex string literal with capturing group

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. eg

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);
}
  1. Use a delimeter that does not occur in the string. Eg R"~( .... )~"

  2. You still need to escape the \\ for regex. To match \\ literally use \\\\ .

  3. You probably want to stop as soon as the shortest possible match is found. So use (.*?) :

     std::regex re(R"~(some\\\\"string"name":"(.*?)"\\\\"lastname":"doe")~");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM