Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string to dictionary using multiple separators as a key

Tags:

string

c#

I have string 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 dictionary where separator is key and value is from given string. Also there is possibility that one of the separators is not in the text.

I know how to split it into sentence but don't know how to handle situation when one of the separators is missing and how to split it to dictionary.

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

EDIT1: Sample with missing separator:

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

EDIT2 I forget that some separators can be two words :(. If it make easier I can ask to change separators to be written by uppercase letter:

var givenString = "ID: some id TITLE: sometitle CRITERIA: some criteria <br>more criteria, DIFFERENT CRITERIA: some criteria <br>more criteria"
like image 622
kendzi Avatar asked Mar 13 '26 10:03

kendzi


1 Answers

In order to split on pattern (letters A..Za..z followed by 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);

Outcome:

Key = Id           Value = "some id"
Key = Title        Value = "sometitle"
Key = Descritpion  Value = "some description"
Key = Criteria     Value = "some criteria <br>more criteria"
like image 121
Dmitry Bychenko Avatar answered Mar 14 '26 22:03

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!