user3685285
user3685285

Reputation: 6626

C# Regex.Replace case insensitive as a function of the match

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?

Upvotes: 2

Views: 781

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

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.

Upvotes: 7

Related Questions