开发者

filter out trailing slash and number

so my urls will look like:

/hello-world/blah/
/hello-world/blah
/hello-world/blah/234
/h开发者_StackOverflow中文版ello-world/234

IF the url has a trailing slash followed by numbers, I need to return the same string but with the slash and numbers removed.

so the last 2 lines should now look like:

/hello-world/blah
/hello-world

How can I get everything BUT the trailing slash and numbers (if they are present)


How about:

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

Note the $ here, which means that the slash and digits have to be at the end of the string. That will prevent them being removed from the middle of a URL, as demonstrated in the following tests:

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

Results:

/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

EDIT: I wouldn't expect this to be a bottleneck in your code. You might want to create the regular expression once though, and reuse it:

private static readonly Regex TrailingSlashAndDigits = 
    new Regex(@"/\d*$", RegexOptions.Compiled);

and then use

url = TrailingSlashAndDigits.Replace(url, "");

You could try using IsMatch first, but I doubt it would make much odds - I'd definitely only go to that extra level of complexity if you found that this was a bottleneck. Unless your code does little other than this, I doubt that'll be the case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜