Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am using following code to Highlighting keywords in a text or resume.

My code:

string keywords = ".net";
        string text = "These are technologies: .net, intranet, NET, net,ASP.net.";

        Response.Write(HighlightKeywords(keywords, text));
     


private static string HighlightKeywords(string text,string keywords)
    {
        // Swap out the ,<space> for pipes and add the braces
        Regex r = new Regex(@", ?");
        keywords = "(" + r.Replace(keywords, @"|") + ")";

        // Get ready to replace the keywords
        r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);

        // Do the replace
        return r.Replace(text, new MatchEvaluator(MatchEval));
    }

private static string MatchEval(Match match)
    {
        if (match.Groups[1].Success)
        {
            return "<b><font color='red'>" + match.ToString() + "</font></b>";

        }

        return ""; //no match
    }



The output should be shown as

These are technologies: .net, intranet, NET, net,ASP.net.

but it showing as:

These are technologies: .net, intranet, NET, net,ASP.net.

please help me

Thanks in advance

Pankaj

Edit TR - Wrap your code in <pre> tags, like above. It makes it easier to read.
Posted
Updated 6-Apr-10 2:56am
v3

1 solution

You haven't encoded the HTML tags in your example results, but I can guess what is happening: all 5 of the "net"s in the text are being highlighted, whether or not they are a whole word or if they are proceeded by a dot.

The problem is using the keyword string as a regular expression. For example, a dot is a special character in a Regex expression which matches any character - not just a dot!

If you want to use Regex to do this, you will need to do much more processing of the keyword string.

There is a ( free ) program called Expresso that will help you form your expression:

http://www.ultrapico.com/Expresso.htm[^]

Nick
 
Share this answer
 

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