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
我正在尝试编写自己的301重定向。我有2个字符串。一个是旧网址,另一个是新网址。示例如下
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.
像这样,我有很多新老网址。我正在做下面的匹配Urls工作正常。 “redirect”是一个包含旧网址和新网址的字典。
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 个解决方案
#1
1
You have matchedURL, where Key - old url regex, and Value - new url replacement pattern.
你有匹配的URL,其中Key - old url regex和Value - new url replacement pattern。
You can use Regex.Replace method, which accepts 3 string parameters.
您可以使用Regex.Replace方法,该方法接受3个字符串参数。
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);
}
#1
1
You have matchedURL, where Key - old url regex, and Value - new url replacement pattern.
你有匹配的URL,其中Key - old url regex和Value - new url replacement pattern。
You can use Regex.Replace method, which accepts 3 string parameters.
您可以使用Regex.Replace方法,该方法接受3个字符串参数。
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);
}