Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace query parameter with another value/token

Tags:

c#

regex

url

I am trying to replace a URL query pattern wID=xxx, where xxx can be a digit, number or white space, with the query wID=[[WID]] (note that the query is case sensitive). I would like to know how can I achieve this. Currently, I am using regex to find the pattern in the URL and replace it using Regex.Replace() as follows:

private const string Pattern = @"wID=^[0-9A-Za-z ]+$";
private const string Replace = @"wID=[[WID]]";
/// <summary>
/// Extension method to evaluate the url token for wid
/// </summary>
/// <param name="rawUrl">Incoming URL</param>
/// <returns>Expected URL</returns>
public string GetUrl(string rawUrl)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }

    string result = Regex.Replace(rawUrl, Pattern, Replace);
    return result;
}

But this isn't giving me the desired output, as the regex pattern is incorrect, I suppose. Any better way to do this?
My question was related to the implementation of regex pattern to find and replace the URL query parameter value, I found the URI builder is more helpful in these cases and can be used rather so it's different question.

like image 454
Darshak Avatar asked Sep 11 '25 22:09

Darshak


2 Answers

As @maccettura said, you can use a built in. Here we will use HttpUtility.ParseQueryString to parse the parameters then we set the value and finally we replace the query.

Try it online!

public static void Main()
{
    Console.WriteLine(GetUrl("http://example.org?wID=xxx"));
}

/// <summary>
/// Extension method to evaluate the url token for wid
/// </summary>
/// <param name="rawUrl">Incoming URL</param>
/// <returns>Expected URL</returns>
public static string GetUrl(string rawUrl)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }
    var uriBuilder = new UriBuilder(rawUrl);
    var queryString = HttpUtility.ParseQueryString(uriBuilder.Query);
    queryString.Set("wID", "[[WID]]");
    uriBuilder.Query = queryString.ToString();
    return uriBuilder.Uri.ToString();
}

output

http://example.org/?wID=[[WID]]
like image 83
aloisdg Avatar answered Sep 14 '25 12:09

aloisdg


There are better ways of doing this. Have a look at parsing the query string using a NameValueCollection:

 var queryStringCollection = HttpUtility.ParseQueryString(Request.QueryString.ToString());
 queryStringCollection.Remove("wID");
 string newQuery = $"{queryStringCollection.ToString()}&wID=[[WID]]";
like image 36
Reinder Wit Avatar answered Sep 14 '25 11:09

Reinder Wit