C# 用于将路由模板与请求路径匹配的正则表达式
我需要在C# 用于将路由模板与请求路径匹配的正则表达式,c#,regex,C#,Regex,我需要在C中构建一个正则表达式,以匹配下面的url对示例 // 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/pat
C
中构建一个正则表达式,以匹配下面的url对示例
// 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!!!]
我试过使用这个正则表达式,但它在上面的ex03这样的多次出现中都不起作用
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");
这是一个简单的问题。
我希望我的正则表达式能够匹配多个事件。我必须在那里添加哪些模式?请仔细检查您的代码,尤其是调用的方式-输入字符串应该放在第一位,而模式是第二个参数 为了匹配所有字符,应将替换字符串从
修改为至少+
。实际上,我建议将范围缩小到[^/]+
(请参阅):
上述代码输出:
Result 1: True
Result 2: True
Result 1: True
Result 2: True