我有一个方法允许用户指定一个远程目录和一个带有 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/