3

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

2 Answers 2

11

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Andrew: Looks like you're replacing keys, not values. Please adjust.
@David: are you sure? It looks right to me. The parentheses around the possible ? or & and the key in the regex allows Andrew to include the original key in the replacement string using the backreference $1. The old value is discarded by only including the new value in the replacement string.
@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#?
@brism, Andrew: I may have been off my rocker earlier today. What I currently see in this answer is correct.
if I get a blank value in my query string so &foo= is this going to fail to match ?
2

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 URL split in C#?.

2 Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.