C# Regex - Replace with itself

2019-07-18 20:31发布

问题:

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>");

回答1:

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>");


回答2:

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



标签: c# regex replace