Feb 21, 2013

Highlight Search Keyword Using Regular Expression Class in ASP.NET

Most of the time, all of us give searching facility in our web applications. While displaying results we often need to highlight the matched keywords. Though there can be lots of ways to display matched keywords highlighted but the best one I feel is using Regular Expression. Other methods like using Instr / IndexOf etc. are bit complex and required looping with in the string but RegEx class gives a very clear approch for the solution. RegEx Class have a method called Replace, which returns the input string with replacement to matching expression.

Now the question arise is how to replace all the occurences of matched keywords in single string and the answer is using MatchEvaluator.

Replace method accepts parameter like input string (String to be searched) and MatchEvaluator.
MatchEvaluator can be any method in which each match is examined and returns either the orignal string or the replacement string.

Dim basestring as String="The Quick Brown Fox Jumps Right Over the Lazy Dog."
' RegEx Class constructor with 2 parameters
1. String to Search
2. Options like Case Sensitive, Multiline etc, Here we are ignoring casing.

Dim reg As New Regex("(" & Searchstring & ")", RegexOptions.IgnoreCase)
Dim Newstring as string = reg.Replace(basestring, New MatchEvaluator(AddressOf matcheval))

Public Function matcheval(ByVal match As Match) As String
    If match.Groups(1).Success Then
        Return "<strong>" & match.ToString & "</strong>"
        Return match.ToString
    End If
End Function

Download Sample Code Here

Hope, it may be useful.


Blogs | About Me | My Projects | Contact Me