如何解析cpprestsdk生成的多个Set-Cookie?

时间:2018-05-03 10:54:18

标签: c++ regex httpcookie cpprest-sdk

# draw first barplot, getting back the value
bp <- barplot(-2:2, width = n, space = .2)

# get the xlim
x_rg <- par("usr")[1:2]

# plot the "frame"
plot(0, 0, type="n", axes=FALSE, xlab="", ylab="", xlim=x_rg, xaxs="i", ylim=range(as.vector(pr_bp2)))

# plot the groups of bars, one at a time, specifying space, with a correction according to width, so that each group start where it should
sapply(1:5, function(i) barplot(pr_bp2[, i, drop=FALSE], beside = TRUE, width = n[i]/4, space = c((bp[i, 1]-n[i]/2)/(n[i]/4), rep(0, 3)), add=TRUE))

有两个由','连接的Set-Cookie项目,此字符串的问题是过期日期还包含','。

此字符串由cpprestsdk库生成。我需要解析它并生成一个'Cookie'标题,以便在正在进行的请求中发送给服务器。

tgw_l7_route=d0bf4a9ab78d53762b596c0a48dabcdf; Expires=Thu, 03-May-2018 11:42:51 GMT; Path=/, session=a1d25e28-0084-421d-ae71-9ae18c7f6b50; Expires=Sun, 03-Jun-2018 10:42:51 GMT; HttpOnly; Path=/

以上代码输出:

// Example program
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main()
{
  std::string cookieStr = "tgw_l7_route=d0bf4a9ab78d53762b596c0a48dabcdf; Expires=Thu, 03-May-2018 11:42:51 GMT; Path=/, session=a1d25e28-0084-421d-ae71-9ae18c7f6b50; Expires=Sun, 03-Jun-2018 10:42:51 GMT; HttpOnly; Path=/";
  std::regex rgx(", [^ ]+=");
  std::sregex_token_iterator iter(cookieStr.begin(),
    cookieStr.end(),
    rgx,
    -1);
  std::sregex_token_iterator end;
  for ( ; iter != end; ++iter)
    std::cout << *iter << '\n';
}

有没有办法在第二个字符串中保留“session =”?

1 个答案:

答案 0 :(得分:2)

您需要将您使用的模式包装到positive lookahead非消费构造中。

"(?=, [^ ]+=)"
 ^^^        ^

此构造匹配字符串中紧跟着,,空格,然后是空格以外的1 +字符的位置,然后是=符号,不带将匹配的值推入匹配堆栈。这意味着匹配的文本不会被拆分,并且它仍然保留在生成的拆分块数组中。

请参阅regex demo

C++ demo

std::string cookieStr = "tgw_l7_route=d0bf4a9ab78d53762b596c0a48dabcdf; Expires=Thu, 03-May-2018 11:42:51 GMT; Path=/, session=a1d25e28-0084-421d-ae71-9ae18c7f6b50; Expires=Sun, 03-Jun-2018 10:42:51 GMT; HttpOnly; Path=/";
std::regex rgx("(?=, [^ ]+=)");
std::sregex_token_iterator iter(cookieStr.begin(),
  cookieStr.end(),
  rgx,
  -1);
std::sregex_token_iterator end;
for ( ; iter != end; ++iter)
    std::cout << *iter << '\n';

输出:

tgw_l7_route=d0bf4a9ab78d53762b596c0a48dabcdf; Expires=Thu, 03-May-2018 11:42:51 GMT; Path=/
, session=a1d25e28-0084-421d-ae71-9ae18c7f6b50; Expires=Sun, 03-Jun-2018 10:42:51 GMT; HttpOnly; Path=/