by Viper
5. March 2009 12:10
Well this was some question that somebody asked in forums. Well I thought i will just do a quick implementation to show it is done. Here is the use case. You have a text string my leader is not here and leaders of leader1 are gone as well but sleaders not. And you need to find all instances in the string where word leader appears. Just finding if word leader appears or not is simple. You can use IndexOf method to quickly find it. But requirement is that you want to find all occurances with complete word. So for your search of leader should return me list leader,leaders,leader1,sleaders. I just extended the original problem statement to include sleaders meaning that I want to find word even if search word leader is not at the start of the word.
The solution is simple and requires use of RegularExpressions. See the following code snippet.
private static StringCollection FindText(string src, string keyword, bool atStart)
{
StringCollection results = new StringCollection();
string pattern = string.Empty;
if (atStart)
{
pattern = "(" + keyword + ")(?<1>\\w*)";
}
else
{
pattern = "(\\w*)" + "(" + keyword + ")(?<1>\\w*)";
}
MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(src, pattern);
foreach(Match m in matches)
{
results.Add(m.ToString());
Console.WriteLine(m.ToString());
foreach(Group gp in m.Groups)
{
Console.WriteLine(gp);
foreach(Capture c in gp.Captures)
{
Console.WriteLine(c.ToString());
}
}
}
return results;
}
There is lot of noise in the code with all Console.WriteLine statements.But that is all to show what matches, groups and captures are being done by the regular expression. Third parameter of this method controls the pattern. If you set to true, that would mean that you are only interested in result of the search string appears at start of the word. If you will set it to false, it will find the search string anywhere in a word.
|
|
|