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

2 Answers 2

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>");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.