using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; public class Test { public static void Main() { var text = "The Dog is a real-pet animal. There's an undogging dog that only undogs non-dogs. It is one of the most obedient animals. There are many kinds of dogs in the world. Some of the are very friendly while some of them a dangerous. Dogs are of different color like black, red, white and brown. Some old them have slippery shiny skin and some have rough skin. Dogs are carnivorous animals. They like eating meat. They have four legs, two ears and a tail. Dogs are trained to perform different tasks. They protect us from thieves b) guarding our house. They are loving animals. A dog is called man's best friend. They are used by the police to find hidden things. They are one of the most useful animals in the world. Doggonit!"; var searchTerm = "dog"; var searchEntireWord = false; Console.WriteLine("======= 10 ========"); var results = ExtractTexts(text, searchTerm, 10, searchEntireWord); foreach (var result in results) Console.WriteLine(result); Console.WriteLine("======= 15 ========"); results = ExtractTexts(text, searchTerm, 15, searchEntireWord); foreach (var result in results) Console.WriteLine(result); } public static List ExtractTexts(string text, string searchTerm, int sizeOfResult, bool searchEntireWord) { var expression = string.Format(@"(?si)(?() .Select(x => Regex.Replace(x.Value, searchEntireWord ? string.Format(@"(?i)(?$&")) .ToList(); } }