views:

520

answers:

2

In C#, I'm trying to use regular expressions to replace values in a querystring. So, if I have:

http://www.url.com/page.aspx?id=1

I'd like to write a function where I pass in the url, the querystring value and the value to replace. Something along the lines of:

string url = "http://www.url.com/page.aspx?id=1";
string newURL = ReplaceQueryStringValue(url, "id", "2");

private string ReplaceQueryStringValue(string url, string replaceWhat, string replaceWith)
{
    return Regex.Replace(url, "[^?]+(?:\?"+replaceWhat+"=([^&]+).*)?",replaceWith);
}
+2  A: 

It might be easier to use String.Split to initially cut the URL into page and query string parts, and then use Split.String again to cut the query string into distinct parts.

var urlSplit = url.Split('?');
var originalURL = urlSplit[0];

var urlRedefined = url;   
if(urlSplit.Length == 2)
{
  var queryString = urlSplit[1].Split('&');

  //your code here

  var urlRedefined = String.Format("{0}?{1}", 
    originalURL, 
    String.Join("&", queryString);
}

A regular expression may be overkill for your needs. Also, the System.Uri class might be a better fit. Its use is covered in http://stackoverflow.com/questions/1029909/url-split-in-c.

David Andres
I probably could use String.Split. Why would regex be overkill?
@unknown: I mean overkill in that regex patterns are notoriously painful to get right. You might see success in limited testing, but then some small thing can throw your code off. My answer doesn't give you an easy way to take a querystring's name (e.g,. "Id") and replace its value, so perhaps another approach will be more successful.
David Andres
@unknown: Apparently, I've been proven wrong by Andrew Hare.
David Andres
+2  A: 

Here is a function that would do the job:

static string replace(string url, string key, string value)
{
    return Regex.Replace(
     url, 
     @"([?&]" + key + ")=[^?&]+", 
     "$1=" + value);
}
Andrew Hare
@Andrew: Looks like you're replacing keys, not values. Please adjust.
David Andres
brism
@brism - Thanks, that is exactly what is going on. @GordonG - I am curious about the edit, are you aware that `string` and `String` are synonymous in C#?
Andrew Hare
@brism, Andrew: I may have been off my rocker earlier today. What I currently see in this answer is correct.
David Andres