private static string GetSnippet(string text, string fullSearchString)
{
const int beforeStart = 100;
const int afterEnd = 100;
if (text.Length <= afterEnd + beforeStart)
{
return text;
}
var searchString = fullSearchString.Trim().Split(' ')[0].Trim('\'').Trim('"').Trim('*');
// Find first position of the keyword
int index;
var pattern = string.Format("\\b{0}\\b", searchString);
var match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
index = match.Index;
}
else
{
index = text.IndexOf(searchString, StringComparison.InvariantCulture);
}
if (index < 0)
{
index = 0;
}
var textLength = text.Length;
// Crop snippet from the whole search text
var takeFromEnd = (index + afterEnd < textLength) ? 0 : afterEnd - (textLength - index);
var startFrom = index - beforeStart - takeFromEnd;
var addToEnd = 0;
if (startFrom < 0)
{
startFrom = 0;
}
if (startFrom < beforeStart)
{
addToEnd = beforeStart - startFrom;
}
var endWith = index + afterEnd + addToEnd;
if (endWith > textLength)
{
endWith = textLength;
}
if (startFrom > 0)
{
var spaceIndex = text.LastIndexOf(" ", startFrom, StringComparison.InvariantCulture);
if (spaceIndex > 0)
{
startFrom = spaceIndex;
}
}
if (endWith < textLength)
{
var spaceIndex = text.IndexOf(" ", endWith, StringComparison.InvariantCulture);
if (spaceIndex > 0)
{
endWith = spaceIndex;
}
}
var snippet = text.Substring(startFrom, endWith - startFrom);
if (startFrom > 0)
{
snippet = string.Concat("...", snippet);
}
if (endWith < textLength)
{
snippet = string.Concat(snippet, "...");
}
return HttpUtility.HtmlDecode(snippet);
}