Gabe
Gabe

Reputation: 173

Convert string to dictionary in C#

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

Answers (1)

Roel Schlijper
Roel Schlijper

Reputation: 56

You could do it like this:

  • get the key:value pairs with a Regex and put them in a dict
  • Regex.Replace all the key:value pairs with an empty string -> what's left is your content results

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

Related Questions