iFinity Blogs 

Regex for Parsing Url Query Strings

Feb 20

Written by:
Wednesday, February 20, 2008 4:44 PM  RssIcon

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.

Tags:
Categories:
Location: Blogs Parent Separator Crafty Code

2 comment(s) so far...


Gravatar

Re: Regex for Parsing Url Query Strings

You didn't properly encode the in your regex.

I believe you wanted: @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))"

By Ronn Black on   Tuesday, September 15, 2009 4:53 AM
Gravatar

Re: Regex for Parsing Url Query Strings

Ok... One more try to post the correction.

@"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))"


The correction (if the above doesn't display as expected) is to replace { and } the less than and greater than in the following
@"(?:\&|\?)(?:(?{key}.[^\=\&]*)\=(?{val}.[^\=\&]*))"

By Ronn Black on   Tuesday, September 15, 2009 5:00 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel