Q:

Regex for matching a route template with a request path

I need to build a regex in C# for matching these examples of url pairs below.
// Ex 01
// Route Template :      "/path/{id}/path2"
// Actual Request Path : "/path/1512312/path2"
// expected result = [match]

// Ex 02
// Route Template :      "/{name}/path/path2"
// Actual Request Path : "/damon/path/path2"
// expected result = [match]

// Ex 03
// Route Template :      "/path/{name}/{id}/path2"
// Actual Request Path : "/path/damon/1512312/path2"
// expected result = [match]

// Ex 04
// Route Template :      "/path/{name}/{id}/path2"
// Actual Request Path : "/path/damon/path2"
// expected result = [doesn't match!!!]

I tried with this regex, but it doesn't work on multiple occurrences like Ex 03 above.
var regex = new Regex("\\{.*?\\}");
string replacedRouteTemplate = regex.Replace("/path/{name}/{id}/path2", ".");

// this result below becomes false... when matching the Ex 03 example.
bool result = Regex.IsMatch(replacedRouteTemplate , "/path/damon/1512312/path2"); 

// Single occurrence works fine. the IsMatch returns "true" this time.
replacedRouteTemplate = regex.Replace("/path/{id}/path2", ".");
result = Regex.IsMatch(replacedRouteTemplate, "/path/1512312/path2");

It's a simple question.
I want my regex to be able to match multiple occurrences. Which patterns do I have to add there?

A:

Please double-check your code, especially the way Regex.IsMatch is invoked - an input string should go on the first place, whereas a pattern is the second argument.
In order to match all chars, the replacement string should be revised from . to at least .+. I'd actually suggest narrowing it down to [^/]+ (see demo):
var regex = new Regex("\\{.*?\\}");
string replacedRouteTemplate = regex.Replace("/path/{name}/{id}/path2", "[^/]+");

bool result = Regex.IsMatch("/path/damon/1512312/path2", replacedRouteTemplate);
Console.WriteLine($"Result 1: {result}");

replacedRouteTemplate = regex.Replace("/path/{id}/path2", "[^/]+");
result = Regex.IsMatch("/path/1512312/path2", replacedRouteTemplate);
Console.WriteLine($"Result 2: {result}");

The code above outputs:
Result 1: True
Result 2: True

