【问题标题】:String Pattern Matching using basic String Operations使用基本字符串操作的字符串模式匹配
【发布时间】:2013-04-18 07:50:49
【问题描述】:

我有一个方法允许用户指定一个远程目录和一个 searchPattern with with 来搜索远程目录中的文件。由于我在从远程位置检索文件名时使用第三方库,因此我无法利用 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;
}

提前致谢。

【问题讨论】:

  • 请具体说明要求。请问这个方法怎么称呼?
  • 正则表达式?在线搜索模式有数千种。
  • @NikhilAgrawal - 我认为这并不重要。问题的本质似乎是“我如何全局匹配字符串”
  • 什么意思我怎么称呼这个方法?当 SearchPattern 是用户提供的任意字符串模式时,我如何使用正则表达式,我想尽可能地匹配?

标签: c# .net string pattern-matching match


【解决方案1】:

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

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

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

【讨论】:

  • 那么在 SearchPattern 类似于 24April2013##_*.mp4 的情况下会发生什么?
  • 我假设# 应该代表一个数字?您可以在末尾添加另一个 .Replace("#", @"\d") 以将其转换为正则表达式版本。
【解决方案2】:

如果您可以指定此方法将接受哪些类型的搜索字符串,则可以使用正则表达式。为了简洁起见,这是一个使用 Linq 的示例:

public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase)
{
    var options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
    return thirdPartyTool.ftpClient.GetCurrentDirectoryContents()
                         .Where(fn => Regex.Matches(fn, SearchPattern, options))
                         .ToList();
}

即使您无法控制此方法接受哪些类型的搜索字符串,将搜索字符串转换为正则表达式仍然可能比编写您自己的匹配模式的算法更容易。有关如何执行此操作的详细信息,请参阅 Bobson 的答案。

【讨论】:

  • 这要求输入搜索字符串的最终用户知道正则表达式。
猜你喜欢
  • 2013-10-13
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多