2013-03-24 74 views
0

我想寫我自己的301重定向。我有2個字符串。一個是舊的網址,另一個是新的網址。這個例子是下面RegEx.Replace問題 - 自定義URL重寫

原始地址:

procurement-notice-(\d+).html 

新的URL:

/Bids/Details/$1 

這樣的,我有很多新老網址的。我正在做以下匹配工作正常的網址。 「重定向」是一個包含新舊網址的字典。

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

但現在我想用新的網址替換匹配的網址。

回答

1

您已匹配URL,其中Key - 舊URL正則表達式和Value - 新URL替換模式。

您可以使用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 
    } 
} 

,代碼可能會是這樣的:

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

+1正是這就是我所期待的。這麼快.. – Karthick 2013-03-24 10:14:25