我試圖找到具有特定關鍵字的文本的某個部分。我做到了,但我認爲可能有更好的方法來做到這一點。使用正則表達式和C返回部分文本#
這裏是我的代碼,
/// <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;
}
尋找你的那種建議,以改善它。
爲什麼你需要'minLength' ... – Anirudha
http://codereview.stackexchange.com/ –
http://codereview.stackexchange.com/;) –