views:

55

answers:

3

I am currently using this regex to get the page number from the url:

 @"\/(\d+)$";

Which worked fine for urls like:

/some_category/2
/some_category2/323

My urls now have some additional querystring values (optionally), so the current regex is not working for these cases.

So now I need a regex to support:

/some_category/2
/some_category2/323
/some_category2/323?a=1&b=2
/some_category2/323?&c=123&a=1&b=2

Any help would be appreciated.

I am using a route with wildcards so I can use the built in asp.net mvc for this.

+4  A: 

It should be /(\d+)

No need to escape the front slash. The $ character was an end-of-line character which wasn't working because the digits occurred before the end of the line

SimpleCoder
A: 

Try this one. Works in JavaScript.

@"/(\d+)\??.*$";
Jan Kuča
+2  A: 

If you're using MVC, why do you need a Regex for the URL at all? Can't you simply get the number in your ActionResult?

Assuming your Route is

// Default Catch All MapRoute
routes.MapRoute("Default", "{controller}/{action}/{id}", new {
    controller = "Home",
    action = "Index",
    id = UrlParameter.Optional
})

Then just use

public ActionResult myAction(int id){
    // get your "number" by using the "id" variable
}
rockinthesixstring
+1No Regex needed here and actually the Regex would be a bad practice.
Stilgar
regex also adds significant overhead where it isn't needed. The querystring will still behave as expected, but you can also retrieve URL parameters from your route without too much effort.
rockinthesixstring
I said I was using a wildcard route, that is why, thanks.
Blankman
at the top I asked if we could see your route. sometimes there's a way to avoid using a wildcard route and still get the same behavior. If you can reduce system overhead by not using regex, you'll probably be happy with the outcome down the road... it might just mean that you need to "tweak" your routes.
rockinthesixstring