Search code examples
c#regexsearchsplittags

TextBox that searches through file names despite tags order


I have a C# .Net application with images. Images are named like "cat bowl.jpg" "bowl dog.jpg" "possum.jpg" "raccoon bowl night.jpg" I want to create a search textbox to search through the names when I write something.

For example if I write "dog night" I want to see "bowl dog.jpg" and "raccoon bowl night.jpg"

I tried to do it with regex

string[] imageFiles = Directory.GetFiles(imageFolderPath, "*.jpg");
string searchText = searchTextBox.Text;
foreach (string imageFile in imageFiles)
{
   string pattern = @"" + searchPhrases +"";
   Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);   
   if (regex.IsMatch(imageFile)) {
//code

but it's not working like I wanted it to work I know there is String.Contains() but it's also not working the way I want it to I'm looking for something like searching images by tags


Solution

  • You could split the search string and into individual words and do string.Contains with each individual word:

    var searchWords = searchText.Split(" ");
    var matches = imageFiles.Where(f => searchWords.Any(w => f.Contains(w, stringComparison.CurrentCultureIgnoreCase)));
    

    That should give you the desired result without any need for complicated regex. You might also consider some kind of scoring, so that better matches appear higher up in the result list, and/or some kind of fuzzy string matching if you want to allow strings close enough.