使用正则表达式提取所有cookie属性

ca9*_*3d9 -2 c# regex f#

例如,如果我有一个cookie字符串

"lu=Rg3vHJ; Expires=Tue, 15-Jan-2013 21:47:38 GMT; Path=/; Domain=.example.com; HttpOnly"
Run Code Online (Sandbox Code Playgroud)

如何提取以下列表中的所有cookie属性:

NameValuePair // Mandatory "lu" and "Rg3vHJ"
Domain // ".example.com"
Path // "/"
Expires // "Tue, 15-Jan-2013 21:47:38 GMT"
MaxAge // Not exist in the example
Secure // Not exist
HttpOnly // Exists
Run Code Online (Sandbox Code Playgroud)

不确定"Set-Cookie"中属性的顺序是否固定.如果表达式可以按任何顺序丢失(如果除主名称/值对之外可能缺少所有其他属性),如何编写表达式?

我需要将值分配给C#struct或F#record.

struct { 
    KeyValuePair<string, string> NameValue, // mandatory 
    string Domain,
    string Path,
    string Expires,
    string MaxAge,
    bool Secure,
    bool HttpOnly
}
Run Code Online (Sandbox Code Playgroud)

F#

type Cookie = {
    NameValue : string * string;
    Domain : string option;
    Path : string option;
    Expires : string option;
    MaxAge : string;
    Secure : bool; // ? no associated value, anything better than bool
    HttpOnly : bool; // ? no associated value, anything better than bool
    }
Run Code Online (Sandbox Code Playgroud)

EZI*_*EZI 5

string cookie = "lu=Rg3vHJ; Expires=Tue, 15-Jan-2013 21:47:38 GMT; Path=/; Domain=.example.com; HttpOnly";
var parts = cookie.Split(';')
            .Select(x => x.Split('='))
            .ToDictionary(x => x[0].Trim(), x => x.Length > 1 ? x[1].Trim() : "");

Console.WriteLine(String.Join(Environment.NewLine, parts.Select(x => x.Key + "=" + x.Value)));
Run Code Online (Sandbox Code Playgroud)

或者在评论中发布你的正则表达式

var pattern = @"(.+?)(?:=(.+?))?(?:;|$|,(?!\s))";

var parts = Regex.Matches(cookie, pattern).Cast<Match>()
                 .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
Run Code Online (Sandbox Code Playgroud)