Reputation: 173
I'm trying to incorporate a Twitter-esque advanced search feature in the Admin area of my website that is used for comment moderation. This is what a search would look like:
yeah that guy sucks username:john_doe ip:78.931.345.23 item:43
How would I go about converting that string to a dictionary that would be comprised of this:
{"content", "yeah that guy sucks"},
{"username", "john_doe"},
{"ip", "78.931.345.23"},
{"item", "43"}
I know this would involve declaring a dictionary and adding to it in a for
loop, but I don't know an easy way to get from a string to a dictionary like such.
I was first thinking of popping the "yeah that guy sucks" then splitting the string by spaces so there'd be a variable and an array that would look this this:
string content = "yeah that guy sucks";
string[] parameters = ["username:john_doe", "ip:78.931.345.23", "item:43"];
...then I'd split each element of the array by a colon so it would look this this:
[["username","john_doe"], ["ip","78.931.345.23"], ["item","43"]];
But the problem with the above solution is I wouldn't know when the content
part of the string (which is optional, mind you) "yeah that guy sucks" ends.
I figured there is a much easier way to do this, perhaps with the help of regular expressions which I'm not good at yet. Any suggestions?
Upvotes: 0
Views: 1018
Reputation: 56
You could do it like this:
RoelS
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;
}
Upvotes: 3