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
Welcome to my blog and project site for Microsoft.NET development.

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

Extract Keywords from a Search String in C#

By steve on January 27, 2007.
Updated on January 22, 2012.
Viewed 28,250 times (1 times today).
Article AttributesArticle AttributesArticle TypesLanguage ElementsLanguage ElementsLanguagesTechnologies
Has DownloadsHas ImagesSnippetRegular ExpressionsText and StringsC#.NET

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

User Comments (5)

Posted 2009 Nov 01 09:50 AM. reply
Mmmmm.... Nice!

Nick1Alive
Posted 2011 Feb 17 11:41 AM. reply
Whats wrong with String.split(newline)?

Steve
Replied 2011 Feb 17 11:43 AM by Steve. reply
Should have been wrong with text.split(" ")?
Reply 2011 Dec 20 12:11 PM by steve. reply
Well, that's another way, but it doesn't handle multiple spaces or extra whitespace nicely. You'll end up with empty keywords in the array of strings.
Posted 2011 Dec 30 03:08 AM. reply
StringSplitOptions.RemoveEmptyEntries removes such entries: text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)

aegir
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.