我知道我能做到
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中。我只是不知道它是在哪里暴露的。
将模式转换为正则表达式可能是一种方法。然而,它似乎只是有很多边缘情况,可能会有更多的麻烦比它的价值。
注意:问题中的文件名可能还不存在,所以我不能只包装一个Directory.GetFiles调用,然后检查结果集是否有任何条目。
发布于 2013-03-27 04:26:39
最简单的方法是将通配符转换为正则表达式,然后应用它:
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;
}
}发布于 2013-03-27 04:39:51
我不认为GetFiles的searchPattern支持完整的正则表达式。下面的代码可以是另一种选择(但性能不是很好)
bool IsMatch(string fileName,string searchPattern)
{
try
{
var di = Directory.CreateDirectory("_TEST_");
string fullName = Path.Combine(di.FullName, fileName);
using (File.Create(fullName)) ;
bool isMatch = di.GetFiles(searchPattern).Any();
File.Delete(fullName);
return isMatch;
}
catch
{
return false;
}
}https://stackoverflow.com/questions/15646555
复制相似问题