4

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.

8
  • You shouldnt use Regex for this, there are already built in libraries that help you parse URIs. If you include a sample URL I can provide a regex-less answer Commented Jun 21, 2018 at 14:40
  • A sample URL is "fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=123" The position of wID can be anywhere in the URL Commented Jun 21, 2018 at 14:56
  • Do you need the [ and ] to be escaped? Commented Jun 21, 2018 at 15:00
  • input = "fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=123" output = "fod.infobase.com/…" Commented Jun 21, 2018 at 15:01
  • I've seen the URL, I am asking if you want the resulting url to have the [ and ] characters escaped? Commented Jun 21, 2018 at 15:02

4 Answers 4

3

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

2 Comments

What if you got another query parameter name similiar to 'wID' (e.g. 'qwID')?
Probably better to .Remove("wID") then manually prepend wID=[[WID]]&, unfortunately you cannot assign [[WID]] directly as it will get escaped.
2

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]]";

2 Comments

ParseQueryString actually uses a specialized Http collection that will escape [ and ] when you .Set.
good point @AlexK. I didn't even notice that. I've updated my answer
2

I will toss my own answer in since its a bit more re-usable and it does not escape the brackets ([]):

public static string ModifyUrlParameters(string rawUrl, string key, string val)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }

    //Builds a URI from your string
    var uriBuilder = new UriBuilder(rawUrl);        

    //Gets the query string as a NameValueCollection
    var queryItems = HttpUtility.ParseQueryString(uriBuilder.Uri.Query);

    //Sets the key with the new val
    queryItems.Set(key, val);

    //Sets the query to the new updated query
    uriBuilder.Query = queryItems.ToString();

    //returns the uri as a string
    return uriBuilder.Uri.ToString();
}

An input of: http://example.org?wID=xxx

Results in: http://example.org/?wID=[[WID]]

Fiddle here

Comments

0

You don't need a Regex for that.

var index = rawUrl.IndexOf("wID=");
if (index > -1)
{
   rawUrl = rawUrl.Substring(0, index + 4) + "[[WID]]";
}

1 Comment

This does not seem right. Why are you starting at the beginning of rawUrl for your substring? Why is it hardcoded to a 4 length?

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.