2009-06-05 100 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