The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. -- Edsger Dijkstra
NinjaTrader Kickstart - Use your dev skills to trade the markets. This is my latest free course. I hope you'll try it out - Steve @ CambiaResearch

Extract Keywords from a Search String in C#



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


Version: 5.1.20191022.2156