如何:
url = Regex.Replace(url, @"/\d*$", "");
請注意$這裏,這意味着斜槓和數字必須位於字符串的末尾。這將防止他們從URL的中間被刪除,如表現在以下測試:
using System;
using System.Text.RegularExpressions;
public class Test
{
static void Main()
{
TestUrl("/hello-world/blah/");
TestUrl("/hello-world/blah/234");
TestUrl("/hello-world/234");
TestUrl("/hello-world/234/blah");
TestUrl("/hello-world/12/34");
}
static void TestUrl(string url)
{
string transformed = Regex.Replace(url, @"/\d*$", "");
Console.WriteLine("{0} => {1}", url, transformed);
}
}
結果:
/hello-world/blah/ => /hello-world/blah
/hello-world/blah/234 => /hello-world/blah
/hello-world/234 => /hello-world
/hello-world/234/blah => /hello-world/234/blah
/hello-world/12/34 => /hello-world/12
編輯:我不希望這是一個瓶頸您碼。你可能會想,雖然一次創建正則表達式,並重新使用它:
private static readonly Regex TrailingSlashAndDigits =
new Regex(@"/\d*$", RegexOptions.Compiled);
然後用
url = TrailingSlashAndDigits.Replace(url, "");
你可以嘗試使用IsMatch
第一,但我懷疑它會多大勝算 - 我d 絕對是只有當你發現這是一個瓶頸時纔會出現更高的複雜程度。除非你的代碼除了這個以外沒有其他的東西,否則我懷疑是這樣。
只是執行正則表達式替換,還是先執行regex.IsMatch會更快? – mrblah 2010-01-01 21:33:14
@mrblah:這真的是你的代碼中的僵局嗎?更多的編輯... – 2010-01-01 21:33:42