【问题标题】:How to parse multiple Set-Cookie generated by cpprestsdk?如何解析 cpprestsdk 生成的多个 Set-Cookie?
【发布时间】:2018-05-03 10:54:17
【问题描述】:
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=/

Set-Cookie 中有 2 项由 ', ' 连接,这个字符串的问题是过期日期也包含 ', '。

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

// 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';
}

以上代码输出:

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

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

【问题讨论】:

  • 或者,有没有办法通过模式“,[^]+=”的开头来分割字符串?
  • 你似乎需要"(?=, [^ ]+=)""(?=,\\s*\\S+=)"
  • @WiktorStribiżew,太好了,谢谢! ", (?=[^ ]+=)" 有效。这是什么术语?
  • 积极的前瞻。

标签: c++ regex httpcookie cpprest-sdk


【解决方案1】:

您需要将您使用的模式包装到一个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=/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2019-07-04
    • 2012-09-02
    • 2016-07-19
    • 2018-12-10
    相关资源
    最近更新 更多