2

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>");
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Orbiter
  • 49
  • 3
  • 4

2 Answers2

8

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>");
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76