过滤掉斜杠和数字

时间:2010-01-01 21:24:37

标签: c# regex

所以我的网址看起来像:

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

如果url后面有数字后跟斜杠,我需要返回相同的字符串,但是删除了斜杠和数字。

所以最后两行现在应该是这样的:

/hello-world/blah
/hello-world

如何获得所有内容但是尾部斜线和数字(如果它们存在)

1 个答案:

答案 0 :(得分:6)

怎么样:

url = Regex.Replace(url, @"/\d*$", "");

注意$ here,这意味着斜杠和数字必须位于字符串的末尾。这将阻止它们从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,但我怀疑这会产生很大的困难 - 如果你发现这是一个瓶颈,我肯定只能达到额外的复杂程度。除非你的代码除此之外没什么用,否则我怀疑情况会是这样。