johnny 5
johnny 5

Reputation: 21033

Convert Route Templates into Regex

I have an application with ~300 of services. I would like to add authorization for a specific subroute. I've created a custom authorization attribute to to verify routes. I would like to convert the route templates to regex, so I can assure that any changes in the future will be automatically be applied back to the authorization attribute.

e.g I have a route.

var benefitRoute =  "/employees/{employeeId:Guid}/benefit/{benefitId:guid}/enrollments";

I would like to replace all of the {} and their contents with .*

"/employees/.*/benefit/.*/enrollments";

However I tried to match on \{.+\} However it grabs the larger one before the two smaller ones, when I run my regex.

Regex.Replace(route, "\{.+\}", ".*");

How can I convert the route templates into Regex.

Upvotes: 0

Views: 167

Answers (1)

dahan raz
dahan raz

Reputation: 392

You should add '?' which makes quantifiers "lazy", try

        var benefitRoute =  "/employees/{employeeId:Guid}/benefit/{benefitId:guid}/enrollments";
        string pattern = @"{(.*?)}";
        String result=Regex.Replace(benefitRoute, pattern, ".*");

You can find more info on it here http://www.regular-expressions.info/repeat.html

Upvotes: 2

Related Questions