I have this:
Title = Regex.Replace(Title, s, "<span style="background:yellow">" + s + "</span>", RegexOptions.IgnoreCase);
Where s is a word like facebook. If the title is:
How to make a Facebook game
I would like to replaced to:
How to make a <span style="background:yellow">Facebook</span> game
Even if the search word is ‘facebook’ (note capitalisation). Basically, how do I retain the original capitalisation of the word?
Another example, search term FACEBOOK, string Hello FaCeBoOk is turned to Hello <span style="background:yellow">FaCeBoOk</span>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use the $& substitution for that:
Regex.Replace(Title, s, "<span style="background:yellow">$&</span>", RegexOptions.IgnoreCase)
Method 2
You can simply include a capture group that matches the word “facebook”, and include that capture group as part of the replacement string. This will end up including it in the end result exactly as it appeared in the input.
var title = "How to make a Facebook game";
title = Regex.Replace(title,
"(facebook)",
"<span style="background:yellow">$1</span>",
RegexOptions.IgnoreCase);
Method 3
var input = "How to make a Facebook game, do you like facebook?";
var searchFor = "facebook";
var result = Regex.Replace(
input,
searchFor,
"<span style="background:yellow">$+</span>",
RegexOptions.IgnoreCase);
The only important thing is the $+. It contains the last acquired text. This will work even for “How to make a Facebook game, do you like facebook?” The first Facebook will be left upper-case, the second one will be left lower-case.
I’ll add that if you want to look only for whole words, then you can make:
searchFor = @"b" + searchFor + @"b";
This will look only for strings that are on word boundary.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0