tags:

views:

39

answers:

1

Hi,

I have a longer text and some keywords. I want to highlight these keywords in my text. That is no problem with this code:

        private static string HighlightKeywords2(string keywords, string text)
        {
            // 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(MatchEval2));
        }


        private static string MatchEval2(Match match)
        {
            if (match.Groups[1].Success)
            {
                return "<b>" + match.ToString() + "</b>";
            }

            return ""; //no match
        }

But when the word"tournament" is in the text and the keyword "tour" it becomes <b>tour</b>nament. I want to it to highlight the complete word: <b>tournament</b>.

How can I do this?

+1  A: 

You could add a \w* before and after each keyword. That way, the entire word would match if it contains a keyword.

Edit: In your code,

keywords = "(\\w*" + r.Replace(keywords, @"\w*|\w*") + "\\w*)"; 

should do it.

Jens
Can you show me in the code?
Philip
I can.. editing =)
Jens
Works like a charm! Thanks!
Philip
Just had to add one more backslash: keywords = "(\\w*" + r.Replace(keywords, @"\w*|\w*") + "\\w*)";
Philip