1

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?

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Couldn't you just use $0 which should contain the entire match - no need to add parentheses?
0

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

1 Comment

Not sure you have read my question properly. I aw aware that North is being replaced to north.
0

Try this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.