C++正则表达式字符串字面值和捕获组

3

我有一个包含反斜杠和双引号的std::string字符串。 我想使用捕获组提取子字符串,但是我无法得到正确的语法。

例如:

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);
}

4
不要使用正则表达式来解析 JSON。请使用专门的 JSON 解析器进行解析。 - Lightness Races in Orbit
1个回答

6
  1. Use a delimeter that does not occur in the string. E.g. 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")~");
    

R"..."语法是什么?它是否必要? - kirugan
2
R"..."是新的字面字符串语法。如果没有它,"\"将需要变成"\\" :( - rustyx
那么唯一的分隔符只需要在 std::regex re 或者 std::string str 中使用吗?还是在任何使用 R 的地方都需要? - ontherocks
@ontherocks 在使用 R 的任何地方。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接