More advanced Contain string function

Just thought I share this useful function I’ve been using recently to enhance some of my applications to make text/string searching more powerful.

If you want to allow things like ‘and’, ‘or’ and ‘not’ in a text filter this could be useful to you. Additionally I also added keywords for things like ‘matchexactly’, ‘startswith’ and ‘endswith’.

public static class StringCompareUtils
{
  public static bool ContainEx(string source, string findText, bool caseSensitive = false)
  {
    bool found = false;
    string lowerCasefindText = findText.ToLower();
    if (findText.Trim().Length == 0)
    {
      found = true;
    }
    else if (lowerCasefindText.Contains(" and "))
    {
      string[] parts = findText.Split(new string[] { " and ", " AND " }, StringSplitOptions.RemoveEmptyEntries);
      found = true;
      foreach (string part in parts)
      {
        if (!ContainEx(source, part))
        {
          found = false;
          break;
        }
      }
    }
    else if (lowerCasefindText.Contains(" or "))
    {
      string[] parts = findText.Split(new string[] { " or ", " OR " }, StringSplitOptions.RemoveEmptyEntries);
      foreach (string part in parts)
      {
        if (ContainEx(source, part))
        {
          found = true;
          break;
        }
      }
    }
    else
    {
      if (lowerCasefindText.TrimStart().StartsWith("not "))
      {
        found = !source.ContainEx2(findText.TrimStart().Substring(4), caseSensitive);
      }
      else
        found = source.ContainEx2(findText, caseSensitive);
    }
    return found;
  }
  private static bool ContainEx2(this string text, string findText, bool caseSensitive = false)
  {
    string matchText = caseSensitive ? text : text.ToLower();
    string matchFindText = caseSensitive ? findText : findText.ToLower();
    if (matchFindText.ToLower().StartsWith("matchexactly "))
    {
      return text == findText.Substring("matchexactly ".Length);
    }
    else if (findText.ToLower().StartsWith("startswith "))
    {
      return text.StartsWith(findText.Substring("startswith ".Length));
    }
    else if (findText.ToLower().StartsWith("endswith "))
    {
      return text.EndsWith(findText.Substring("endswith ".Length));
    }
    else
    {
      return text.Contains(findText);
    }
  }
}

The default behavior is like the ‘like’ operator (text contains search filter). This allow you to find a string like ‘are’ in ‘You are welcome’. Using this function you can specify a filter like ‘startswith You’ or ‘endswith welcome’.

Leave a Reply

%d bloggers like this: