You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET实现无视关键词顺序的图片文件名搜索文本框

实现C# .NET图片文件名的标签式搜索

要实现你需要的标签式搜索(按空格分隔关键词,匹配包含指定关键词的文件名),可以通过拆分关键词+逐一匹配的方式实现,比正则更直观且不易出错,以下是两种常见场景的实现方案:

方案1:匹配包含任意关键词的文件(符合你的示例需求)

当输入"dog night"时,会匹配所有包含dog或night的文件:

string imageFolderPath = "你的图片文件夹路径";
string searchText = searchTextBox.Text.Trim();
// 拆分关键词,自动过滤空内容(处理多个空格的情况)
string[] searchKeywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

// 获取所有jpg文件
string[] imageFiles = Directory.GetFiles(imageFolderPath, "*.jpg");

foreach (string imageFile in imageFiles)
{
    // 提取不含路径和扩展名的纯文件名
    string fileName = Path.GetFileNameWithoutExtension(imageFile);
    
    // 检查文件名是否包含任意一个关键词(不区分大小写)
    bool isMatch = searchKeywords.Any(keyword => 
        fileName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0);
    
    if (isMatch)
    {
        // 执行匹配成功后的逻辑,比如显示图片
    }
}

方案2:匹配包含所有关键词的文件

如果需要严格匹配同时包含所有关键词的文件(比如输入"bowl dog"仅匹配"bowl dog.jpg"),只需把Any替换为All:

bool isMatch = searchKeywords.All(keyword => 
    fileName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0);

正则实现方式(可选)

如果你偏好使用正则,需正确构建匹配模式,避免原代码中未处理关键词拆分的问题:

任意关键词匹配

// 转义关键词避免正则特殊字符干扰,用|分隔实现"或"逻辑
string pattern = string.Join("|", searchKeywords.Select(Regex.Escape));
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
bool isMatch = regex.IsMatch(fileName);

所有关键词匹配

// 用正向预查实现"且"逻辑,确保所有关键词都存在
string pattern = string.Join("", searchKeywords.Select(k => $"(?=.*{Regex.Escape(k)})"));
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
bool isMatch = regex.IsMatch(fileName);

原方案问题说明

你之前的代码存在两个核心问题:

  1. 未将搜索文本拆分为独立关键词,直接使用searchPhrases构建正则无法实现多关键词匹配;
  2. 未对关键词进行正则转义,若关键词包含.、*等特殊字符会导致匹配错误。

而直接使用String.Contains()只能匹配完整的搜索文本,无法拆分关键词进行匹配,所以也不符合需求。

内容的提问来源于stack exchange,提问作者Neon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:53:22