相当于.NET的PathMatchSpec

时间:2009-06-05 05:58:43

标签: .net search

有人知道.NET中的Windows API函数PathMatchSpec()是否具有相同的功能吗?

4 个答案:

答案 0 :(得分:0)

如果使用正则表达式无法获得功能(我相信是这种情况)如何通过PInvoke使用PathMatchSpec()?

http://www.pinvoke.net/default.aspx/shlwapi/PathMatchSpec.html

答案 1 :(得分:0)

您可以尝试 How to implement glob in C# ,或者如果有必要,可以尝试PInvoke route

答案 2 :(得分:0)

我不知道.NET中内置的方法,但使用Regex复制是微不足道的:

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可能更可取。

答案 3 :(得分: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;
    }
}