2

Say I have some text like this:

string text = "Hello world! hElLo world!";

I want to add a span tag around each of the words 'hello' in a case insensitive way so that the result is this:

string text = "<span>Hello</span> world! <span>hElLo</span> world!";

I tried to do this with Regex.Replace like so:

Regex.Replace(text, "hello", "<span>hello</span>", RegexOptions.IgnoreCase);

But what I really need is just the span tags to be created, leaving the original casing alone. So I would need the replace phrase to be a function of the matched phrase. How can I do this?

2
  • 1
    That's not string.Replace. Commented Apr 13, 2017 at 14:24
  • Sorry, just edited Commented Apr 13, 2017 at 14:38

1 Answer 1

7

Instead of hard-coding the hello in the replacement pattern, use a $& backreference to the entire match value.

Replace "<span>hello</span>" with "<span>$&</span>", use

var replaced = Regex.Replace(text, "hello", "<span>$&</span>", RegexOptions.IgnoreCase);

See more about replacement backreferences in Substitutions in Regular Expressions.

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

5 Comments

should be... replace "hello" with "<span>$&</span>"
@AgapwIesu He means replace "<span>hello</span>" with "<span>$&</span>" in the code, not literally use both in the Replace call.
Yes, var replaced = Regex.Replace(text, "hello", "<span>$&</span>", RegexOptions.IgnoreCase);
May I suggest that you add your last comment to your answer.
Sorry, I was ina rush. Added just now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.