.NET中的glob模式匹配

问题描述 投票:42回答:14

.NET中是否有内置机制来匹配正则表达式以外的模式?我想使用UNIX样式(glob)通配符匹配(* =任何数字的任何字符)。

我想将它用于面向最终用户的控件。我担心允许所有RegEx功能会非常混乱。

c# .net glob
14个回答
34
投票

我找到了你的实际代码:

Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );

1
投票

我不知道.NET框架是否有全局匹配,但你不能用*替换*。并使用正则表达式?


1
投票

根据以前的帖子,我把一个C#类放在一起:

using System;
using System.Text.RegularExpressions;

public class FileWildcard
{
    Regex mRegex;

    public FileWildcard(string wildcard)
    {
        string pattern = string.Format("^{0}$", Regex.Escape(wildcard)
            .Replace(@"\*", ".*").Replace(@"\?", "."));
        mRegex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
    }
    public bool IsMatch(string filenameToCompare)
    {
        return mRegex.IsMatch(filenameToCompare);
    }
}

使用它会是这样的:

FileWildcard w = new FileWildcard("*.txt");
if (w.IsMatch("Doug.Txt"))
   Console.WriteLine("We have a match");

匹配与System.IO.Directory.GetFiles()方法不同,因此不要将它们一起使用。


0
投票

从C#开始,您可以使用.NET的LikeOperator.LikeString方法。这是VB的LIKE operator的支持实现。它使用*,?,#,[charlist]和[!charlist]支持模式。

您可以通过添加对Microsoft.VisualBasic.dll程序集的引用来使用C#中的LikeString方法,该程序集包含在每个.NET Framework版本中。然后像任何其他静态.NET方法一样调用LikeString方法:

using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
...
bool isMatch = LikeOperator.LikeString("I love .NET!", "I love *", CompareMethod.Text);
// isMatch should be true.

0
投票

出于好奇,我已经浏览了Microsoft.Extensions.FileSystemGlobbing - 它拖累了很多库的相当大的依赖 - 我已经决定了为什么我不能尝试写类似的东西?

好吧 - 说起来容易做起来难,我很快就注意到它毕竟不是那么简单的功能 - 例如“* .txt”应该只在当前直接匹配文件,而“** .txt”也应该收获子文件夹。

微软还测试了一些奇怪的匹配模式序列,如“./*.txt” - 我不确定谁真正需要“./”类型的字符串 - 因为它们在处理时无论如何都被删除了。 (https://github.com/aspnet/FileSystem/blob/dev/test/Microsoft.Extensions.FileSystemGlobbing.Tests/PatternMatchingTests.cs

无论如何,我已经编写了我自己的函数 - 并且它将有两个副本 - 一个在svn中(我可能稍后会修改它) - 我将在这里复制一个示例以用于演示目的。我建议从svn链接复制粘贴。

SVN链接:

https://sourceforge.net/p/syncproj/code/HEAD/tree/SolutionProjectBuilder.cs#l800(如果没有正确跳转,搜索matchFiles函数)。

这里也是本地功能副本:

/// <summary>
/// Matches files from folder _dir using glob file pattern.
/// In glob file pattern matching * reflects to any file or folder name, ** refers to any path (including sub-folders).
/// ? refers to any character.
/// 
/// There exists also 3-rd party library for performing similar matching - 'Microsoft.Extensions.FileSystemGlobbing'
/// but it was dragging a lot of dependencies, I've decided to survive without it.
/// </summary>
/// <returns>List of files matches your selection</returns>
static public String[] matchFiles( String _dir, String filePattern )
{
    if (filePattern.IndexOfAny(new char[] { '*', '?' }) == -1)      // Speed up matching, if no asterisk / widlcard, then it can be simply file path.
    {
        String path = Path.Combine(_dir, filePattern);
        if (File.Exists(path))
            return new String[] { filePattern };
        return new String[] { };
    }

    String dir = Path.GetFullPath(_dir);        // Make it absolute, just so we can extract relative path'es later on.
    String[] pattParts = filePattern.Replace("/", "\\").Split('\\');
    List<String> scanDirs = new List<string>();
    scanDirs.Add(dir);

    //
    //  By default glob pattern matching specifies "*" to any file / folder name, 
    //  which corresponds to any character except folder separator - in regex that's "[^\\]*"
    //  glob matching also allow double astrisk "**" which also recurses into subfolders. 
    //  We split here each part of match pattern and match it separately.
    //
    for (int iPatt = 0; iPatt < pattParts.Length; iPatt++)
    {
        bool bIsLast = iPatt == (pattParts.Length - 1);
        bool bRecurse = false;

        String regex1 = Regex.Escape(pattParts[iPatt]);         // Escape special regex control characters ("*" => "\*", "." => "\.")
        String pattern = Regex.Replace(regex1, @"\\\*(\\\*)?", delegate (Match m)
            {
                if (m.ToString().Length == 4)   // "**" => "\*\*" (escaped) - we need to recurse into sub-folders.
                {
                    bRecurse = true;
                    return ".*";
                }
                else
                    return @"[^\\]*";
            }).Replace(@"\?", ".");

        if (pattParts[iPatt] == "..")                           // Special kind of control, just to scan upper folder.
        {
            for (int i = 0; i < scanDirs.Count; i++)
                scanDirs[i] = scanDirs[i] + "\\..";

            continue;
        }

        Regex re = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        int nScanItems = scanDirs.Count;
        for (int i = 0; i < nScanItems; i++)
        {
            String[] items;
            if (!bIsLast)
                items = Directory.GetDirectories(scanDirs[i], "*", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            else
                items = Directory.GetFiles(scanDirs[i], "*", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            foreach (String path in items)
            {
                String matchSubPath = path.Substring(scanDirs[i].Length + 1);
                if (re.Match(matchSubPath).Success)
                    scanDirs.Add(path);
            }
        }
        scanDirs.RemoveRange(0, nScanItems);    // Remove items what we have just scanned.
    } //for

    //  Make relative and return.
    return scanDirs.Select( x => x.Substring(dir.Length + 1) ).ToArray();
} //matchFiles

如果你发现任何错误,我会毕业来解决它们。


0
投票

我写了一个解决方案。它不依赖于任何库,它不支持“!”或“[]”运营商。它支持以下搜索模式:

C:\日志\ * TXT

C:?\日志\ ** \ * P1 \ ** \ ASD的* .pdf

    /// <summary>
    /// Finds files for the given glob path. It supports ** * and ? operators. It does not support !, [] or ![] operators
    /// </summary>
    /// <param name="path">the path</param>
    /// <returns>The files that match de glob</returns>
    private ICollection<FileInfo> FindFiles(string path)
    {
        List<FileInfo> result = new List<FileInfo>();
        //The name of the file can be any but the following chars '<','>',':','/','\','|','?','*','"'
        const string folderNameCharRegExp = @"[^\<\>:/\\\|\?\*" + "\"]";
        const string folderNameRegExp = folderNameCharRegExp + "+";
        //We obtain the file pattern
        string filePattern = Path.GetFileName(path);
        List<string> pathTokens = new List<string>(Path.GetDirectoryName(path).Split('\\', '/'));
        //We obtain the root path from where the rest of files will obtained 
        string rootPath = null;
        bool containsWildcardsInDirectories = false;
        for (int i = 0; i < pathTokens.Count; i++)
        {
            if (!pathTokens[i].Contains("*")
                && !pathTokens[i].Contains("?"))
            {
                if (rootPath != null)
                    rootPath += "\\" + pathTokens[i];
                else
                    rootPath = pathTokens[i];
                pathTokens.RemoveAt(0);
                i--;
            }
            else
            {
                containsWildcardsInDirectories = true;
                break;
            }
        }
        if (Directory.Exists(rootPath))
        {
            //We build the regular expression that the folders should match
            string regularExpression = rootPath.Replace("\\", "\\\\").Replace(":", "\\:").Replace(" ", "\\s");
            foreach (string pathToken in pathTokens)
            {
                if (pathToken == "**")
                {
                    regularExpression += string.Format(CultureInfo.InvariantCulture, @"(\\{0})*", folderNameRegExp);
                }
                else
                {
                    regularExpression += @"\\" + pathToken.Replace("*", folderNameCharRegExp + "*").Replace(" ", "\\s").Replace("?", folderNameCharRegExp);
                }
            }
            Regex globRegEx = new Regex(regularExpression, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
            string[] directories = Directory.GetDirectories(rootPath, "*", containsWildcardsInDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            foreach (string directory in directories)
            {
                if (globRegEx.Matches(directory).Count > 0)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                    result.AddRange(directoryInfo.GetFiles(filePattern));
                }
            }

        }
        return result;
    }

62
投票

我喜欢我的代码更加语义,所以我编写了这个扩展方法:

using System.Text.RegularExpressions;

namespace Whatever
{
    public static class StringExtensions
    {
        /// <summary>
        /// Compares the string against a given pattern.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <param name="pattern">The pattern to match, where "*" means any sequence of characters, and "?" means any single character.</param>
        /// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns>
        public static bool Like(this string str, string pattern)
        {
            return new Regex(
                "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                RegexOptions.IgnoreCase | RegexOptions.Singleline
            ).IsMatch(str);
        }
    }
}

(更改命名空间和/或将扩展方法复制到您自己的字符串扩展类)

使用此扩展,您可以编写如下语句:

if (File.Name.Like("*.jpg"))
{
   ....
}

只是糖,使你的代码更清晰:-)


23
投票

只是为了完整。自2016年以来,在dotnet core有一个名为Microsoft.Extensions.FileSystemGlobbing的新nuget包,支持高级全球路径。 (Nuget Package

一些例子可能是,搜索在Web开发场景中非常常见的通配符嵌套文件夹结构和文件。

  • wwwroot/app/**/*.module.js
  • wwwroot/app/**/*.js

这有点类似于.gitignore文件用于确定从源代码管理中排除哪些文件。


10
投票

GetFiles()EnumerateDirectories()这样的列表方法的2和3参数变体将搜索字符串作为支持文件名通配的第二个参数,包括*?

class GlobTestMain
{
    static void Main(string[] args)
    {
        string[] exes = Directory.GetFiles(Environment.CurrentDirectory, "*.exe");
        foreach (string file in exes)
        {
            Console.WriteLine(Path.GetFileName(file));
        }
    }
}

会屈服

GlobTest.exe
GlobTest.vshost.exe

The docs表示有一些匹配扩展的警告。它还指出8.3文件名是匹配的(可能在幕后自动生成),这可能导致给定某些模式的“重复”匹配。

支持这个的方法是GetFiles()GetDirectories()GetFileSystemEntries()Enumerate变体也支持这一点。


5
投票

如果使用VB.Net,则可以使用Like语句,它具有类似Glob的语法。

http://www.getdotnetcode.com/gdncstore/free/Articles/Intoduction%20to%20the%20VB%20NET%20Like%20Operator.htm


4
投票

我写了一个FileSelector类,它根据文件名选择文件。它还根据时间,大小和属性选择文件。如果你只想要文件名通配,那么你用“* .txt”等类似的形式表达名称。如果你想要其他参数,那么你指定一个布尔逻辑语句,如“name = * .xls和ctime <2009-01-01” - 暗示在2009年1月1日之前创建的.xls文件。你也可以根据负面选择: “name!= * .xls”表示不是xls的所有文件。

看看这个。开源。自由执照。在别处免费使用。


3
投票

如果你想避免正则表达式,这是一个基本的glob实现:

public static class Globber
{
    public static bool Glob(this string value, string pattern)
    {
        int pos = 0;

        while (pattern.Length != pos)
        {
            switch (pattern[pos])
            {
                case '?':
                    break;

                case '*':
                    for (int i = value.Length; i >= pos; i--)
                    {
                        if (Glob(value.Substring(i), pattern.Substring(pos + 1)))
                        {
                            return true;
                        }
                    }
                    return false;

                default:
                    if (value.Length == pos || char.ToUpper(pattern[pos]) != char.ToUpper(value[pos]))
                    {
                        return false;
                    }
                    break;
            }

            pos++;
        }

        return value.Length == pos;
    }
}

像这样使用它:

Assert.IsTrue("text.txt".Glob("*.txt"));

3
投票

我已经为.NETStandard编写了一个用于测试和基准测试的通配库。我的目标是为.NET创建一个具有最小依赖性的库,它不使用正则表达式,并且优于Regex。

你可以在这里找到它:


2
投票

https://www.nuget.org/packages/Glob.cs

https://github.com/mganss/Glob.cs

GNU Glob for .NET。

您可以在安装后删除软件包引用,只需编译单个Glob.cs源文件。

因为它是GNU Glob的一个实现,所以当你发现另一个类似的实现时,它就是跨平台和跨语言!

© www.soinside.com 2019 - 2024. All rights reserved.