0

I have a simple search & replace function which find & replaces the search keyword with keyword wrapped around <span></span> tag so that match is highlighted in different color

sample code

private string GetHighlightedText(string text, string keyword)
{
    if (keyword != null)
    {
        Regex regex = null;
        string pattern = @"(\b(?:" + keyword + @")\b)(?![^<]*?>)";
        regex = new Regex(pattern, RegexOptions.IgnoreCase);
        text = regex.Replace(text, "<span class='keyword-highlight'>$1</span>");
    }
    return text;
}

This function at moment matches the whole world & replaces the match with the <span class='keyword-highlight'>$1</span>

let us say i am looking for for Global Villa then it should also highlight part of text Global Village as <span class='keyword-highlight'>Global Villa</span>ge

Learning
  • 19,469
  • 39
  • 180
  • 373
  • 1
    Then remove the second `\b` if you want to make sure the search phrase is found when it is followed with word chars. – Wiktor Stribiżew Oct 10 '19 at 09:50
  • @WiktorStribiżew, removed `\b` it didnt work – Learning Oct 10 '19 at 09:54
  • @WiktorStribiżew, it works if i remove the second one, My mistake i didnt pick your reply right.. Its working if i remove second instance – Learning Oct 10 '19 at 09:56
  • Yes, it works - http://ideone.com/PYDLrg. Just check again [where word boundary matches](https://stackoverflow.com/a/1324784/3832970). Bear in mind `\b` is context dependent, and often leads to unexpected matches/non-matches – Wiktor Stribiżew Oct 10 '19 at 09:56

0 Answers0