Karthick
Karthick

Reputation: 443

RegEx.Replace issue - Custom URL rewrite

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.

Upvotes: 0

Views: 516

Answers (1)

Alexander
Alexander

Reputation: 4173

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);
}

Upvotes: 1

Related Questions