2009-06-05 103 views

回答

0

我不知道內置於.NET的方法不過是微不足道用正則表達式來複制:

public static bool PathMatchSpec(String path, String spec) 
{ 
    String specAsRegex = Regex.Escape(spec).Replace("\\*", ".*").Replace("\\?", ".") + "$"; 
    return Regex.IsMatch(path, specAsRegex); 
} 

顯然,這種假設System.Text.RegularExpressions命名空間被引用。如果你打算用相同的規格做很多事情,你也可以緩存正則表達式。

編輯添加:P/Invoke確實是一個選項,但PathMatchSpec的簽名指示它需要一個ANSI字符串,所以您會爲每個調用引發字符集轉換。請記住,如果你走這條路。在這種情況下,PathMatchSpecEx可能會更好。

+0

酷......我自己並不知道Escape()方法;肯定會簡化我的解決方案的一部分;) – jerryjvl 2009-06-05 06:15:13

0

總之......不,我知道的......但也許這可以幫助你一起(注意,一個更長一點比你可能想,但它使我受益匪淺):

sealed public class WildcardMatch 
{ 
    private static Regex wildcardFinder = new Regex(@"(?<wildcards>\?+|\*+)", RegexOptions.Compiled | RegexOptions.Singleline); 
    private Regex wildcardRegex; 

    public WildcardMatch(string wildcardFormat) : this(wildcardFormat, false) { } 

    public WildcardMatch(string wildcardFormat, bool ignoreCase) 
    { 
     if (wildcardFormat == null) 
      throw new ArgumentNullException("wildcardFormat"); 

     StringBuilder patternBuilder = new StringBuilder("^"); 
     MatchCollection matches = this.wildcardFinder.Matches(wildcardFormat); 
     string[] split = this.wildcardFinder.Split(wildcardFormat); 
     for (int ix = 0; ix < split.Length; ix++) 
     { 
      // Even indexes are literal text, odd indexes correspond to matches 
      if (ix % 2 == 0) 
       patternBuilder.Append(Regex.Escape(split[ix])); 
      else 
      { 
       // Matches must be substituted with Regex control characters 
       string wildcards = matches[ix/2].Groups["wildcards"].Value; 
       if (wildcards.StartsWith("*", StringComparison.Ordinal)) 
        patternBuilder.Append("(.*)"); 
       else 
        patternBuilder.AppendFormat(CultureInfo.InvariantCulture, "({0})", wildcards.Replace('?', '.')); 
      } 
     } 
     patternBuilder.Append("$"); 

     this.wildcardRegex = new Regex(
      patternBuilder.ToString(), 
      RegexOptions.Singleline | (ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None)); 
    } 

    public bool IsMatch(string value) 
    { 
     if (value == null) 
      return false; 

     return this.wildcardRegex.IsMatch(value); 
    } 

    public IEnumerable<string> ExtractMatches(string value) 
    { 
     if (value == null) 
      yield break; 

     Match match = this.wildcardRegex.Match(value); 
     if (!match.Success) 
      yield break; 

     for (int ix = 1; ix < match.Groups.Count; ix++) 
      yield return match.Groups[ix].Value; 
    } 
} 
+0

請注意,通過使用anelsons的Regex.Escape()'轉義代碼可以絕對簡化。 – jerryjvl 2009-06-05 06:15:51