Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple regex replace to keep original string

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>

like image 309
Tom Gullen Avatar asked Sep 11 '11 17:09

Tom Gullen


1 Answers

You can use the $& substitution for that:

Regex.Replace(Title, s, "<span style=\"background:yellow\">$&</span>", RegexOptions.IgnoreCase)
like image 76
svick Avatar answered Nov 10 '22 00:11

svick