Search code examples
regexasp.net-mvcmaproute

Regular expression to avoid "Images" in controller name


In this moment I have the next MapRoute

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults
            new { controller = @"[^\.]*" }                          // Parameter constraints 
        );

My defined constraint is controller = @"[^.]*"

I need a constraint to avoid also the controllers with the name "Images".

How can I do this??


Solution

  • There is no need for the backslash to escape the dot since the dot has no special meaning in a character class.

    For this, you can use a negative lookahead:

    new { controller = @"(?!Images)[^.]*" }
    

    A negative lookahead is an anchor, in the sense that like ^ or $, it will not consume text in the regex, it is looking for a position in the input text. Another name for lookarounds are zero-width assertions.