Pessimists, we're told, look at a glass containing 50% air and 50% water and see it as half empty. Optimists, in contrast, see it as half full. Engineers, of course, understand the glass is twice as big as it needs to be. --Bob Lewis

Extract Keywords from a Search String in C#

Downloads

Summary

When a user enters a string into a textbox to initiate a search, the developer has to parse that string and convert it to a query of some kind. This little snippet uses a very simple regular expression to extract the keywords from the search string as an array of strings. From this array you can then create your search query.

public static string[] GetSearchWords(string text)
{
   string pattern = @"\S+";
   Regex re = new Regex(pattern);

   MatchCollection matches = re.Matches(text);
   string[] words = new string[matches.Count];
&nbsp;&nbsp;&nbsp;for (int i=0; i<matches.Count; i++)
&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;words[i] = matches[i].Value;
&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;return words;
}

Dont' forget the using directive:

using System.Text.RegularExpressions