c# - 使用基本字符串操作的字符串模式匹配

标签 c# .net string pattern-matching match

我有一个方法允许用户指定一个远程目录和一个带有 with 的 searchPattern 来搜索远程目录中的文件。由于我在从远程位置检索文件名时使用第三方库,因此我无法利用 System.IO 的 Directory.GetFiles() 例程,该例程允许我在获取文件时指定 searchPattern。

Basic String.Compare 不能将文件名与提供的模式正确匹配。有人知道更有效的匹配方法吗?

public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase)
{
    IList<String> matchingFileNames = new List<String>();

   var RemoteFiles = thirdPartyTool.ftpClient.GetCurrentDirectoryContents();

    foreach( String filename in RemoteFiles)
     if( String.Compare(filename, SearchPattern, ignoreCase) == 0)
            matchingFileNames.Add(filename);

    return matchingFileNames;
}

提前致谢。

最佳答案

使用通配符(*, ?)的文件匹配称为“glob”匹配或“globbing”。您可以尝试将用户输入的 glob 搜索转换为正则表达式,然后使用它。有一个例子 here :

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

然后这将作为模式传递到 RegEx.Match() 中,您当前在其中有 String.Compare()

关于c# - 使用基本字符串操作的字符串模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16197459/

相关文章:

c# - Visual Studio 不会使用 ReadOnlyAttribute(true) 使属性变灰

c# - LINQ自引用表过滤关系

c# - .NET 中的 System.nanoTime() 等效于什么?

c# - 定制异常消息未显示在控制台中

c++ - 生成特定长度的 powerset

c# - 警告 "Message template is not a compile time constant"

c# - 将 lambda 表达式用于事件处理程序

.net - 什么时候不实现通用接口(interface)?

c - 由于 strcpy 和 strcat 导致的段错误

c++ - 传递 const char* 作为模板参数