Skip to content
Amal Hashim
All posts
Snippet

C# - Regular expression to replace HTML tags

Replace all b tags with strong tags in C# using a lazy regular expression that also works across line breaks.

1 min read#.NET#C#

The task: find every b tag in some HTML and replace it with strong. Input:

html
<b>This is a bold text</b> Lorem Ipsum is simply dummy text
<b>some more bold text</b>
Lorem Ipsum is simply dummy text <b> again bold text </b>

Expected output:

html
<strong>This is a bold text</strong> Lorem Ipsum is simply dummy text
<strong>some more bold text</strong>
Lorem Ipsum is simply dummy text <strong> again bold text </strong>

A plain string replace does not cover every case. Splitting and parsing each token needs a lot of code and fails on corner cases. A regular expression is the shortest route.

The (.|\n)*? part matches any text, including new lines, as little as possible. That stops one match swallowing the next b tag. The captured text is put back with $1.

csharp
string strRegex = @"\<b\>((.|\n)*?)\<\/b\>";
RegexOptions myRegexOptions = RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strReplace = @"<strong>$1</strong>";
string newstring = myRegex.Replace(inputstring, strReplace);