Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
Hi
we are doing text search and highlight the keyword.

up to this working good.


I used the following code:-

if (Regex.IsMatch(retext, string.Format(@"\b{0}\b";, str, RegexOptions.Singleline)) == true)

{
  Label3.Text = retext.Replace(str, string.Format("<span style="font-weight">

bold;background-color:yellow ;'> {0,1}</span>", str));
                                   

 string strdis = retext.Replace(str, string.Format("", str), RegexOptions.Singleline| 

RegexOptions.IgnoreCase);
                                    
retext = Label3.Text;
                              

}


But the problem is when iam highlight the search keyword,it is highlight the exact keyword also highlight the related sub matching words.


Example:-
Iam searching the keyword "net" but it highlight the words "net" and "nunet" and "netherlands".

When iam searching the keyword with "net" it has to highlight the only "net" in my text.
Please guide me

Thanks in Advance.
Posted
Updated 22-Jun-11 1:35am
v2
Comments
[no name] 22-Jun-11 7:36am    
Edited for code block.

I think \b is enough to get it as word only.
Try
retext = retext.Replace(str, String.Format("\b{0}\b",str), String.Format("<span style="font-weight:bold;background-color:yellow ;">{0,1}</span>", str))
 
Share this answer
 
v3
Comments
Member 7932936 22-Jun-11 8:05am    
where i have to put \b
Prerak Patel 22-Jun-11 8:43am    
I guessed that you used \b{0}\b for constructor too. Anyways, modified.
Manfred Rudolf Bihy 22-Jun-11 10:52am    
Good one! 5+
 
Share this answer
 
Try this pattern for Regex: "\<net\>".
 
Share this answer
 
v2
Just use " " + str + " " in place of str so that the 'str' only with space is replaced.

You have to use the code like this:

XML
if (Regex.IsMatch(retext, string.Format(@"\b{0}\b";, str, RegexOptions.Singleline)) == true)
{
  Label3.Text = retext.Replace(" " + str + " ", string.Format("<span style="font-weight">
bold;background-color:yellow ;'> {0,1}</span>", " " + str + " "));

 string strdis = retext.Replace(" " + str + " ", string.Format("", " " + str + " "), RegexOptions.Singleline
RegexOptions.IgnoreCase);
retext = Label3.Text;

}


Thanks
 
Share this answer
 
Comments
Prerak Patel 22-Jun-11 7:57am    
Regex will replace the text within str. There is no use enclosing it in " "
Tarun Mangukiya 22-Jun-11 8:13am    
Then Directly use as
Label1.text = Label1.text.Replace(" " + str + " ", "<b>" + str + "</b>")

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900