I was trying to find a certain part of the text having a specific keyword. I did it but I am thinking there might be a better way to do it.
Here is my code,
/// <summary>
/// Return String containing the search word
/// </summary>
/// <param name="strInput">Raw Input</param>
/// <param name="searchWord">Search Word</param>
/// <param name="minLength">Output Text Length</param>
/// <returns></returns>
public static String StringHavingSearchPattern(String strInput, String searchWord, Int32 minLength)
{
//considering the return string empty
String rtn = String.Empty;
//
if (String.IsNullOrEmpty(strInput))
{
return rtn;
}
// consider the raw input as return;
//rtn = strInput;
int length = strInput.Length;
//if the rawinput length is greater||equal than/to the min length
if (length >= minLength)
{
int currentSearchIndex = -1;
searchWord = String.Format(@"{0}", searchWord);
//currentSearchIndex = strInput.IndexOf(searchWord,StringComparison.InvariantCultureIgnoreCase);
Match m = Regex.Match(strInput, searchWord, RegexOptions.Multiline | RegexOptions.IgnoreCase);
if (m.Success)
{
currentSearchIndex = m.Index;
if (currentSearchIndex >= 0)
{
if (currentSearchIndex > 9)
{
if ((length - currentSearchIndex - 1) >= minLength)
{
rtn = strInput.Substring((currentSearchIndex - 9), minLength);
}
else
{
rtn = strInput.Substring((currentSearchIndex - 9), length - currentSearchIndex - 1);
}
}
else
{
rtn = strInput.Substring(0, minLength);
}
}
else
{
rtn = strInput.Substring(0, minLength);
}
}
}
rtn = Regex.Replace(rtn, searchWord, String.Format("<span style='color:yellow;background-color:blue;'>{0}</span>", searchWord), RegexOptions.IgnoreCase | RegexOptions.Multiline);
//rtn = rtn.Replace(searchWord, String.Format("<span style='color:yellow;background-color:blue;'>{0}</span>", searchWord));
return rtn;
}
Looking for your kind suggestions to improve it.
Your hunch was right; you can use a single, simple regular expression to achieve this:
This will create, for example for
searchWord“keyword” andminLength10, the following regex,which means, “Capture up to 10 characters followed by ‘keyword’ and the remainder of the text.” Then, you can grab the captured group:
Note that the case where there are less than
minLengthcharacters before the search term is covered.