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.
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]]
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]]";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With