KuljeetSingh.com

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>"
    Else
        Return match.ToString
    End If
End Function

Download Sample Code Here

Hope, it may be useful.

 
?

Blogs | About Me | My Projects | Contact Me
【丰胸】虽然,这些药物对于乳房而言粉嫩公主,能够起到一定的丰胸效果,可朋友们这些药物的后遗症,也会在我们服完后慢慢显现出来丰胸产品,譬如:机体中的雌激素水平被打破了,就容易导致我们的月经变得不正常丰胸食物,从而使得我们的腰跟着变得圆嘟嘟,而严重的话还可能会导致我们的子宫出血,肝脏受损丰胸效果,所以说若是采用药物来进行丰胸,大家还是小心谨慎些为好。