2013-03-26 2 views
1

은 내가파일 이름이 와일드 카드 패턴과 일치하는지 어떻게 확인합니까?

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 호출을 감싸고 결과 집합에 항목이 있는지 확인하지 못할 수 있습니다. 갈

답변

4

가장 쉬운 방법은 정규식하기 위해 와일드 카드를 변환 한 다음 그것을 적용하는 것입니다 :

public static string WildcardToRegex(string pattern) 
{ 
    return "^" + Regex.Escape(pattern). 
    Replace("\\*", ".*"). 
    Replace("\\?", ".") + "$"; 
} 

을하지만 어떤 이유로 정규식을 사용할 수없는 경우, 당신은 와일드 카드 일치의 자신의 구현을 작성할 수 있습니다. here을 찾을 수 있습니다.

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=="") 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; 
    } 
} 
+0

잘못된 파일 이름에는 작동하지 않습니다. 'Match ("aaa/bbb.txt", "* .txt");'는 * true를 반환합니다 * – I4V

+1

원래 질문에는 경로가 포함되지 않고 파일 이름 만 일치합니다. 그러나 Path.GetFileName()을 사용하여 항상 파일 이름을 추출 할 수 있습니다. – Alexander

+0

나는 ** aaa/bbb.txt와 같은 ** 잘못된 ** 파일 이름을 말했다. * * 경로 * – I4V

0

내가 GetFilessearchPattern 전체 정규 표현식을 지원하지 않습니다 생각하지 않는다 :

여기 파이썬 구현에서 포팅 또 다른 하나입니다. 아래 코드는 대안이 될 수 있습니다. (매우 좋은 것은 아닙니다)

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; 
    } 
} 
관련 문제