我知道我能做到
Directory.GetFiles(@"c:\", "*.html")
我会得到一个与 *.html 文件模式匹配的文件列表。
我想做相反的事情。给定文件名 abc.html,我想要一种方法来告诉我该文件名是否与 *.html 模式匹配。比如
class.method("abc.html", "*.html") // returns true
class.method("abc.xml", "*.html") // returns false
class.method("abc.doc", "*.?oc") // returns true
class.method("Jan24.txt", "Jan*.txt") // returns true
class.method("Dec24.txt", "Jan*.txt") // returns false
该功能必须存在于 dotnet 中。我只是不知道它暴露在哪里。
将模式转换为正则表达式可能是一种方法。然而,似乎有很多边缘情况,可能比它的值(value)更麻烦。
注意:问题中的文件名可能还不存在,所以我不能只包装一个 Directory.GetFiles 调用并检查结果集是否有任何条目。
最佳答案
最简单的方法是将通配符转换为正则表达式,然后应用它:
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
但如果由于某种原因不能使用正则表达式,您可以编写自己的通配符匹配实现。你可以找到一个here .
这是从 python 实现移植的另一个(编辑 2020-07:fixed IndexOutOfRangeException):
using System;
class App
{
static void Main()
{
Console.WriteLine(Match("abc.html", "*.html")); // returns true
Console.WriteLine(Match("abc.xml", "*.html")); // returns false
Console.WriteLine(Match("abc.doc", "*.?oc")); // returns true
Console.WriteLine(Match("Jan24.txt", "Jan*.txt")); // returns true
Console.WriteLine(Match("Dec24.txt", "Jan*.txt")); // returns false
}
static bool Match(string s1, string s2)
{
if (s2=="*" || s1==s2) return true;
if (s1=="" || s2=="") return false;
if (s1[0]==s2[0] || s2[0]=='?') return Match(s1.Substring(1),s2.Substring(1));
if (s2[0]=='*') return Match(s1.Substring(1),s2) || Match(s1,s2.Substring(1));
return false;
}
}
关于.net - 如何检查文件名是否与通配符模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646555/