Orbiter
Orbiter

Reputation: 49

C# Regex - Replace with itself

In want to format an article with HTML tags programmatically. What is the best way to find a pattern in the article and replace it with itself with the tags appended on each side? More specifically, how can I pass the match into thematch in the following example:

string formattedArticle
    = Regex.Replace(article, "^\d.+", "<em>" + thematch + "</em>");

Upvotes: 2

Views: 3684

Answers (2)

BartoszKP
BartoszKP

Reputation: 35891

The documentation explains:

The $& substitution includes the entire match in the replacement string.

In fact, in their example they present a use case very similar to yours:

Often, it is used to add a substring to the beginning or end of the matched string.

So in your case you can write:

Regex.Replace(article, "^\d.+", "<em>$&</em>");

Upvotes: 8

Braj
Braj

Reputation: 46841

replace it with itself with the tags appended on each side

Simply capture it inside the group enclosing inside parenthesis (...) and then access it using $1 and replace with <TAG>$1</TAG>

Online demo

sample code:

var pattern = @"^(\d.+)";
var replaced = Regex.Replace(text, pattern, "<em>$1</em>"); 

Read more about Replace only some groups with Regex

Upvotes: 2

Related Questions