0

I am trying to write my own 301 Redirect. I have 2 strings. One is the old url and other one is new url. The example is below

Original Url :

procurement-notice-(\d+).html

New url :

/Bids/Details/$1

like this, i have plenty of old and new url. I am doing the below to match the Urls which works fine. where the "redirect" is a dictionary contains old and new urls.

var matchedURL = redirect.SingleOrDefault(d => Regex.Match(url, d.Key, RegexOptions.Singleline).Success);

but now I want to replace the matched one with the new url.

1 Answer 1

1

You have matchedURL, where Key - old url regex, and Value - new url replacement pattern.

You can use Regex.Replace method, which accepts 3 string parameters.

using System;
using System.Text.RegularExpressions;

class App
{
  static void Main()
  {
    var input = "procurement-notice-1234.html";
    var pattern = @"procurement-notice-(\d+).html";
    var replacement = "/Bids/Details/$1";
    var res = Regex.Replace(input, pattern, replacement);
    Console.WriteLine(res);
    // will output /Bids/Details/1234
  }
}

So in your case, code will probably look like this:

var matchedURL = redirect.SingleOrDefault(d => Regex.Match(url, d.Key, RegexOptions.Singleline).Success);
if (matchedURL != null)
{
  var result = Regex.Replace(url, matchedURL.Key, matchedURL.Value);
}
Sign up to request clarification or add additional context in comments.

Comments

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.