简体   繁体   中英

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?

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.

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.)

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.

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

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]);
}

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('&'))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM