Simple regex replace to keep original string

2019-02-17 03:50发布

问题:

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>

回答1:

You can use the $& substitution for that:

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


回答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);

See it in action.



回答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.