Michel
Michel

Reputation: 23615

c# extract values from key-value pairs in string

i have a string like this:

blablablamorecontentblablabla?name=michel&score=5&age=28&iliedabouttheage=true

looks like a regular query string yes, but i'm not in any web context

now i want to extract the values (after the = sign) by their key , for example,what is the name (michel), the score(5), the age(28) etc.

Normally i parse the string like get the position in the string of the word 'name', then add 5 to it (length of 'name=') and name this position 'start' then search for the &-sign and name that position 'end', and then get the string between the position start and end.

But there must be a better solution, is this a regex thing?

Upvotes: 13

Views: 24752

Answers (7)

Otávio Décio
Otávio Décio

Reputation: 74250

Not really, this can be done just with the Split function (what follows is kinda pseudo code, you need to add bound checks)

string[] query = value.Split('?');
foreach (string pairs in query[1].Split('&')
{
  string[] values = pairs.split('=');
}

Then iterate over the values variable and get the things you need.

Upvotes: 3

LukeH
LukeH

Reputation: 269348

If you want to create a dictionary of the key/value pairs then you could use a bit of LINQ:

Dictionary<string, string> yourDictionary =
    yourString.Split('?')[1]
              .Split('&')
              .Select(x => x.Split('='))
              .ToDictionary(y => y[0], y => y[1]);

(You could skip the Split('?')[1] part if your string contained just the querystring rather than the entire URL.)

Upvotes: 14

Lazarus
Lazarus

Reputation: 43074

I'd probably go down the Split route.

string input = "name=michel&score=5&age=28&iliedabouttheage=true";
string[] pairs = input.Split('&');
Dictionary<string,string> results = new Dictionary<string,string>();
foreach (string pair in pairs) 
{
  string[] paramvalue = pair.Split('=');
  results.Add(paramvalue[0],paramvalue[1]);
}

Upvotes: 2

dcp
dcp

Reputation: 55434

You can use the split method

private static void DoIt()
{
    string x = "blablablamorecontentblablabla?name=michel&score=5&age=28&iliedabouttheage=true";

    string[] arr = x.Split("?".ToCharArray());
    if (arr.Length >= 2)
    {
        string[] arr2 = arr[1].Split("&".ToCharArray());
        foreach (string item in arr2)
        {
            string[] arr3 = item.Split("=".ToCharArray());
            Console.WriteLine("key = " + arr3[0] + " value = " + arr3[1]);
        }
    }
}

Output:

key = name value = michel
key = score value = 5
key = age value = 28
key = iliedabouttheage value = true

Upvotes: 2

Wix
Wix

Reputation: 2214

You could do a split on the '&' and then one on '='. You would have to deal the '?' at the beginning. Or if the string will always 'look' like a querystring then you could still treat it as such and try something like this class QueryString class useful for querystring manipulation, appendage, etc

Upvotes: 0

Eric Petroelje
Eric Petroelje

Reputation: 60498

Try System.Web.HttpUtility.ParseQueryString, passing in everything after the question mark. You would need to use the System.Web assembly, but it shouldn't require a web context.

Upvotes: 35

CodeMonkey1313
CodeMonkey1313

Reputation: 16011

As you suggested, I would recommend regex, probably a pattern like

(?:.)*\?(.*\&.*)*

I know there's something else that can be used to cause the regex to ignore the first part [added, I think], but I can't think of it. That would get you a kvp, then you'd have to split the result on "&" (String.Split('&'))

Upvotes: 1

Related Questions