2010-01-01 37 views
0

所以我的網址看起來像:篩選出斜線和數量

/hello-world/blah/ 
/hello-world/blah 
/hello-world/blah/234 
/hello-world/234 

如果URL中有一個尾隨斜線後面的數字,我需要返回相同的字符串,但是去除了斜線和數字。

所以最後2行現在應該是這樣的:

/hello-world/blah 
/hello-world 

我怎樣才能得到一切,但結尾的斜線和數字(如果存在的話)

回答

6

如何:

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 絕對是只有當你發現這是一個瓶頸時纔會出現更高的複雜程度。除非你的代碼除了這個以外沒有其他的東西,否則我懷疑是這樣。

+0

只是執行正則表達式替換,還是先執行regex.IsMatch會更快? – mrblah 2010-01-01 21:33:14

+0

@mrblah:這真的是你的代碼中的僵局嗎?更多的編輯... – 2010-01-01 21:33:42