Today I did a quite simple search - find me a Regex expression and some C# code to parse all the key/value pairs from a Url Query string. I turned up nothing useful, so here's my contribution to the Google cache.
Sometimes you need to parse a query string that is in a string variable, and don't have access to the Request.QueryString object. In that case, you really want to be able to quickly identify the key/value pairs.
While there are many different ways, here's my take (which is searching for specified terms in the query string, but you could easily modify it to look up by the key value)
using System.Text.RegularExpressions;
//split querystring into key/val matches
//takes url as string
MatchCollection qsItems = Regex.Matches(url, @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))");
foreach (Match itemMatch in qsItems)
{
string val = itemMatch.Groups["val"].Value;
string key = itemMatch.Groups["key"].Value;
switch (key.ToLower())
{
case "tabid":
Int32.TryParse(val, out tabId);
break;
case "portalid":
Int32.TryParse(val, out portalId);
break;
}
}
To lookup on key value, you'd need to use the Regex object and then lookat the GroupNumberByName() function, passing in the name of the group (ie TabId) you are after, then using the resultant number to retrieve the correct Group from the Match.Groups collection.
Most people probably split the Url into an array on the '&' character, but in this case you can just stick the whole Url in and not worry about parsing out all the http://, host, pagename and everything else.