[英]Convert string to dictionary in C#
我正在嘗試在我的網站的管理區域中加入一個 Twitter 式的高級搜索功能,用於評論審核。 這是搜索的樣子:
是的,那個家伙很爛用戶名:john_doe ip:78.931.345.23 項目:43
我將如何 go 將該字符串轉換為包含以下內容的字典:
{"content", "yeah that guy sucks"},
{"username", "john_doe"},
{"ip", "78.931.345.23"},
{"item", "43"}
我知道這將涉及聲明一個字典並在for
循環中添加它,但我不知道從字符串到這樣的字典的簡單方法。
我首先想到的是彈出“是的,那個家伙很爛”,然后用空格分割字符串,這樣就會有一個變量和一個數組,看起來像這樣:
string content = "yeah that guy sucks";
string[] parameters = ["username:john_doe", "ip:78.931.345.23", "item:43"];
...然后我用冒號分割數組的每個元素,所以它看起來像這樣:
[["username","john_doe"], ["ip","78.931.345.23"], ["item","43"]];
但是上述解決方案的問題是我不知道字符串的content
部分(這是可選的,請注意)“是的,那個家伙很爛”什么時候結束。
我想有一種更簡單的方法可以做到這一點,也許可以借助我還不擅長的正則表達式。 有什么建議么?
你可以這樣做:
羅爾斯
private Dictionary<string,string> SplitInput(string input)
{
Dictionary<string, string> searchDict = new Dictionary<string, string>();
string pattern = @"(\w+)[:]([\w,.]+)(\s)?";
var matches = Regex.Matches(input, pattern);
foreach (Match m in matches)
{
string key = m.Groups[1].Value;
string value = m.Groups[2].Value;
searchDict.Add(key, value);
}
string content = Regex.Replace(input, pattern, "").TrimEnd();
searchDict.Add("content", content);
return searchDict;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.