" + s + "", RegexOp...">

Simple regex to keep the original string

I have it:

Title = Regex.Replace(Title, s, "<span style=\"background:yellow\">" + s + "</span>", RegexOptions.IgnoreCase); 

Where s is a word similar to facebook . If the title:

 How to make a Facebook game 

I would like to replace with:

 How to make a <span style="background:yellow">Facebook</span> game 

Even if the search word is facebook (capital letter). Basically, how to keep the initial capital letter of a word?

Another example: the search term facebook , the string Hello FaCeBoOk refers to Hello <span style="background:yellow">FaCeBoOk</span>

+6
source share
3 answers

You can use $& replacement for this:

 Regex.Replace(Title, s, "<span style=\"background:yellow\">$&</span>", RegexOptions.IgnoreCase) 
+6
source
 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 $+ . It contains the last text received. This will work even for "How to make a game on Facebook, do you like facebook?" The first Facebook will remain in upper case, the second in lower case.

I will add that if you want to look only at whole words, you can do:

 searchFor = @"\b" + searchFor + @"\b"; 

This will only look for lines that are on the word boundary.

+1
source

You can simply include a capture group that matches the word facebook and include this capture group in the replacement string part. This will end up in the end being exactly the same as at the entrance.

 var title = "How to make a Facebook game"; title = Regex.Replace(title, "(facebook)", "<span style=\"background:yellow\">$1</span>", RegexOptions.IgnoreCase); 

Look at the action .

+1
source

Source: https://habr.com/ru/post/897098/


All Articles