Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string to find key-value pairs in it

Tags:

string

c#

parsing

While searching mail in Google, we use the sytax like

from:devcoder hasattachments:true mySearchString on:11-aug

or

mySearchString from:devcoder on:11-aug anotherSearchKeyword

After parsing, I should get the keyvalue pair such as (from, devcoder), (on, 11-aug). What is the best way to implement this parsing in c#.

like image 559
matrix Avatar asked Sep 04 '11 15:09

matrix


People also ask

Which data structure is used for key-value pair?

key-value store, or key-value database is a simple database that uses an associative array (think of a map or dictionary) as the fundamental data model where each key is associated with one and only one value in a collection. This relationship is referred to as a key-value pair.

What is key-value pairs?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100).


2 Answers

To Linq-ify Jason's answer:

string s = "from:devcoder hasattachments:true mySearchString on:11-aug";

var keyValuePairs = s.Split(' ')
    .Select(x => x.Split(':'))
    .Where(x => x.Length == 2)
    .ToDictionary(x => x.First(), x => x.Last());
like image 87
lbergnehr Avatar answered Nov 15 '22 05:11

lbergnehr


Split by space, then for each component of the split, split it by :. Then proceed accordingly. Roughly:

string s = "from:devcoder hasattachments:true mySearchString on:11-aug";
var components = s.Split(' ');
var blocks = components.Select(component => component.Split(':'));
foreach(var block in blocks) {
    if(block.Length == 1) {
        Console.WriteLine("Found {0}", block[0]);
    }
    else {
        Console.WriteLine(
            "Found key-value pair key = {0}, value = {1}",
            block[0],
            block[1]
        );
    }
}

Output:

Found key-value pair key = from, value = devcoder
Found key-value pair key = hasattachments, value = true
Found mySearchString
Found key-value pair key = on, value = 11-aug

Output from your second string:

Found mySearchString
Found key-value pair key = from, value = devcoder
Found key-value pair key = on, value = 11-aug
Found anotherSearchKeyword
like image 21
jason Avatar answered Nov 15 '22 03:11

jason