[英]C++ regex string literal with capturing group
I have a std::string containing backslashes, double quotes.我有一个包含反斜杠、双引号的 std::string。 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);
}
Use a delimeter that does not occur in the string.使用不在字符串中出现的分隔符。 Eg
R"~( .... )~"
例如
R"~( .... )~"
You still need to escape the \\
for regex.您仍然需要为正则表达式转义
\\
。 To match \\
literally use \\\\
.要匹配
\\
字面上使用\\\\
。
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")~");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.