How to split a string into a dictionary using multiple delimiters as a key

I have a line that looks like this:

var givenString = "Id: some id Title: sometitle Descritpion: some description Criteria: some criteria <br>more criteria"

      

How can I split it into a dictionary where the delimiter is the key and the value is a given string. It is also possible that one of the delimiters is not in the text.

I know how to split it into a sentence, but I don't know how to deal with a situation where one of the delimiters is missing and how to split it into a dictionary.

string[] separators = { "Id:", "Title:", "Descritpion", "Criteria:" }; 
string[] words = givenString.Split(separators, StringSplitOptions.None);

      

EDIT1: Example with missing separator:

var givenString = "Id: some id Title: sometitle Criteria: some criteria <br>more criteria"

      

EDIT2 I forget that some delimiters can be two words :( If it makes it simpler, I might ask to change the delimiters written with a capital letter:

var givenString = "ID: some id TITLE: sometitle CRITERIA: some criteria <br>more criteria, DIFFERENT CRITERIA: some criteria <br>more criteria"

      

+3


source to share


1 answer


To break into a pattern (letters A..Za..z

followed by a column :

), I suggest using regular expressions, Regex.Split, instead of givenString.Split

:

string givenString = 
  @"Id: some id Title: sometitle Descritpion: some description Criteria: some criteria <br>more criteria";

Dictionary<string, string> result = Regex
  .Split(givenString, "([A-Z][a-z]+ [A-Z][a-z]+:)|([A-Z][a-z]+:)") 
  .Skip(1)                            // <- skip (empty) chunk before the 1st separator
  .Select((item, index) => new {      // pair: separator followed by value 
     value = item.Trim(), 
     index = index / 2 })
  .GroupBy(item => item.index)
  .ToDictionary(chunk => chunk.First().value.TrimEnd(':'), 
                chunk => chunk.Last().value);

      

Test:



string report = string.Join(Environment.NewLine, result
  .Select(pair => $"Key = {pair.Key,-12} Value = \"{pair.Value}\""));

Console.Write(report);

      

Result:

Key = Id           Value = "some id"
Key = Title        Value = "sometitle"
Key = Descritpion  Value = "some description"
Key = Criteria     Value = "some criteria <br>more criteria"

      

+4


source







All Articles