Create a dictionary from a string by separating the string using a word

With the regular expression

^              - start of string
 (.*)          - zero or more characters (Groups[1])
     \s        - whitespace
       (\S*)   - zero or more non-whitespace characters (Groups[2])
            $  - end of string

it is possible to split a string into 2 groups, using the last whitespace in the string as the delimiter.

Using this regular expression, you can use LINQ to process a collection of strings into a dictionary:

var unprocessed = new[] { "7 X 4 @ 70Hz LUVYG" };
var dict =
    unprocessed
        .Select(w => Regex.Match(w, @"^(.*)\s(\S*)$"))
        .Where(m => m.Success)
        .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

Leave a Comment