0

so my urls will look like:

/hello-world/blah/
/hello-world/blah
/hello-world/blah/234
/hello-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)

1 Answer 1

6

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.

2
  • would it be faster to just perform the regex replace, or first do a regex.IsMatch ?
    – mrblah
    Jan 1, 2010 at 21:33
  • @mrblah: Is this really a botteneck in your code? Editing with a bit more on this...
    – Jon Skeet
    Jan 1, 2010 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.