正则表达式处理cookie

时间:2013-10-30 06:23:24

标签: c# regex cookies

我正在使用httpwebreqest / httpwebresponse,问题出在某些网站httpwebresponse无法识别cookie。这就是response.Headers返回的内容。

 Cookie1=1;domain=subdomain.host.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT
 Cookie2= ; HTTPOnly= ; domain=subdomain.host.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT,
 Cookie5= ; domain=.host.com;path=/;HTTPOnly= ;version=1
 Cookie3=2; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=.host.com;path=/;HTTPOnly= ;version=1
 Cookie4=3; domain=.host.com;path=/;version= 

Raw(来自response.Headers的cookie都是单行字符串):

 Cookie1=1;domain=subdomain.host.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT,Cookie2= ; HTTPOnly= ; domain=subdomain.host.com;path=/;Expires=Thu, 30-Oct-1980 16:00:00 GMT,Cookie5= ; domain=.host.com;path=/;HTTPOnly= ;version=1,Cookie3=2; expires=Thu, 30-Oct-1980 16:00:00 GMT;domain=.host.com;path=/;HTTPOnly= ;version=1,Cookie4=3; domain=.host.com;path=/;version= 

以下正则表达式可以完美运行:

(.*?)=(.*?);

但问题是我需要刮掉域名和到期日期,但域名和“过期”会出现在混合位置。如何刮掉所有cookie并获取域名和到期字段?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要以下内容:

@"Cookie(?<index>\d+)\s*=\s*((domain\s*=\s*(?<domain>.*?)[;,])|(expires\s*=\s*(?<expires>.*?GMT))|(.(?!Cookie\d+=)))*"

使用以下选项

RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture

根据您的时间是否都是GMT,您可能希望使用更复杂的内容来捕捉“过期”部分。