To iterate is human, to recurse divine. --L. Peter Deutsch

Extract Keywords from a Search String in C#

By steve on January 27, 2007.
Updated on January 12, 2013.
Viewed 32,747 times (5 times today).
DeveloperTips and TutorialsC#Text

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];
	for (int i=0; i<matches.Count; i++)
	{
		words[i] = matches[i].Value;
	}
	return words;
}

Dont' forget the using directive:

using System.Text.RegularExpressions

Screenshot of sample application in the download

Back to Top
comments powered by Disqus
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more

Subscribe to my email newsletter for news, updates and more!

Sign Up!

Share/Print this page: