views:

51

answers:

3

I am implementing a website search and am trying to highlight the words the user searched for using the below code:

data = Regex.Replace(data, Model.SearchCriteria, "<strong>" + Model.SearchCriteria + "</strong>", RegexOptions.IgnoreCase);

However if data is "I went North towards Canada" and the user has searched for "north" the results will show "I went north towards Canada" with north highlighted however the actual data has been replaced incorrectly slightly.

How can I keep the returned data in tact whilst higlighting what the user searched for?

A: 

You're replacing "North" in the document with the search string "north." Try replacing it with the matched phrase instead of the search phrase.

Sukasa
Not sure you have read my question properly. I aw aware that North is being replaced to north.
Jon
+5  A: 

In this case you need to use a substitution pattern to put the original text into the replaced string vs. the explicit search criteria

data = Regex.Replace(
  "("+Model.SearchCriteria+")",
  "<strong>$1</strong>",
  RegexOptions.IgnoreCase);

Putting parens around the search criteria places it into an unnamed group. You can then reference this group by index in the replacement string by using $1. This will then use the original matched text.

Info on substitution strings in Regex.Replace

JaredPar
Couldn't you just use `$0` which should contain the entire match - no need to add parentheses?
Tim Pietzcker
@Tim, that approach should work as well.
JaredPar
A: 

Try this:

Regex.Replace("I went North towards Canada", "(" + "north + ")", (Match match) =>
{
    return "<strong>" + match.Value + "</strong>";
}, RegexOptions.IgnoreCase);
Rubens Farias