我有一个动态列表,如以下几行
https://www.example.com/ * / post /
https://www.example2.com/videos/ *
https://www.example3.com/photo/
我该如何与以下网址的C#匹配(返回true)
https://www.example.com/user123/post/
http://www.example.com/user123/post/abc
https://www.example2.com/videos/1234
https://www.example2.com/videos/1234/5678
http://www.example2.com/videos/1234/5678
http://example2.com/videos/1234/video.asp?id=1
也许我可以使用UriTemplate,但是url有很多部分。他们没有静态格式。
答案 0 :(得分:0)
尝试使用使用正则表达式的方法:
static void Main(string[] args)
{
var urls = new string[] { "https://www.example.com/*/post/", "https://www.example2.com/videos/*" };
// here regex patterns are created: special characters are escaped and
// star, which means here "anything" is replaced by .+ which means "one or more of any charaters"
var regexes = urls.Select(url => new Regex(url.Replace("/", @"\/").Replace(".", @"\.").Replace("*", ".+")));
var toCheck = new string[]
{
"https://www.example.com/user123/post/",
"http://www.example.com/user123/post/abc",
"https://www.example2.com/videos/1234",
"https://www.example2.com/videos/1234/5678",
"http://www.example2.com/videos/1234/5678",
"http://example2.com/videos/1234/video.asp?id=1"
};
var valid = toCheck.Where(url => regexes.Where(r => r.Match(url).Success).Any()).ToArray();
}