3

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.

Matheus Lacerda
  • 5,983
  • 11
  • 29
  • 45
Darshak
  • 31
  • 5
  • 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 – maccettura Jun 21 '18 at 14:40
  • A sample URL is "https://fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=123" The position of wID can be anywhere in the URL – Darshak Jun 21 '18 at 14:56
  • Do you need the `[` and `]` to be escaped? – maccettura Jun 21 '18 at 15:00
  • input = "https://fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=123" output = "https://fod.infobase.com/PortalPlaylists.aspx?xtid=10112&wID=[[WID]]" – Darshak Jun 21 '18 at 15:01
  • I've seen the URL, I am asking if you want the resulting url to have the `[` and `]` characters escaped? – maccettura Jun 21 '18 at 15:02
  • nope I don't want escaped – Darshak Jun 21 '18 at 15:04
  • Possible duplicate of [Replace item in querystring](https://stackoverflow.com/questions/772253/replace-item-in-querystring) – aloisdg Jun 21 '18 at 15:12
  • string result = Regex.Replace(rawUrl, "wID=[0-9A-Za-z]*", "wID=[[WID]]"); this worked for me – Darshak Jun 21 '18 at 15:27

4 Answers4

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]]
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • What if you got another query parameter name similiar to 'wID' (e.g. 'qwID')? – Freggar Jun 21 '18 at 14:50
  • Probably better to `.Remove("wID")` then manually prepend `wID=[[WID]]&`, unfortunately you cannot assign `[[WID]]` directly as it will get escaped. – Alex K. Jun 21 '18 at 14:51
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]]";
Reinder Wit
  • 6,490
  • 1
  • 25
  • 36
0

You don't need a Regex for that.

var index = rawUrl.IndexOf("wID=");
if (index > -1)
{
   rawUrl = rawUrl.Substring(0, index + 4) + "[[WID]]";
}
Mhd
  • 2,778
  • 5
  • 22
  • 59
  • 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? – maccettura Jun 21 '18 at 14:50
0

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

maccettura
  • 10,514
  • 3
  • 28
  • 35