【发布时间】:2014-10-21 04:21:08
【问题描述】:
我需要解析一个字符串以检索该字符串的所有 value = "pair"。我选择用一个简单的正则表达式来做到这一点。我的正则表达式是正确的,但我不记得如何简单地将我的结果,我的 MatchCollection 转换为一个简单的键值字典。
string headerName = context.Headers["Authorization"];
/* Authorization header
OAuth oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_nonce="K7WmP9YrR2oCYC3", oauth_timestamp="1413801976", oauth_consumer_key="test", oauth_signature="8ad2fZh23q%2FWfK6RykqcvhlLxH4%3D" */
string pattern = "(?<Keyword>\\w+)\\s*=\\s*\\\"(?<Value>\\w+)\\\"";
MatchCollection matches = Regex.Matches(headerName, pattern);
Dictionary<string, string> dictionary = new Dictionary<string,string>();
foreach(Match match in matches)
{
dictionary.Add(match["Keyword"], match["Value"]); // This is wrong
}
【问题讨论】: