C# Regex - Remove Heading Tags

access_time 4 months ago visibility16 comment 0

C# regular expressions can be used to match and replace certain text patterns from a string variable.

Remove heading tags

The following regular expression can be used to remove all heading tags incl. h1 to h9 from HTML text string.

<[hH][1-9][^>]*>[^<]*</[hH][1-9]\s*>

Code snippet

var html = "Your HTML string...";
var regex = new Regex(@"<[hH][1-9][^>]*>[^<]*</[hH][1-9]\s*>", RegexOptions.Compiled | RegexOptions.Multiline
var replacedHtml = regex.Replace(html, "");

Example

Assuming the following is the input string:

Headings:
<h3>Heading h3</h3>    
<h4>LINQ to SQL - Select N Random Records</h4>

After replacement, the output looks like the following:

Headings:
    

Remove tags only

To keep all the text content but to remove all HTML tags, use the following regular expression:

<[^>]*>

Example 

For the above input HTML, the output looks like the following:

Headings:
Heading h3    
LINQ to SQL - Select N Random Records

copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

Follow Kontext

Get our latest updates on LinkedIn or Twitter.

Want to publish your article on Kontext?

Learn more

More from Kontext

Machine Learning with .NET in Jupyter Notebooks
visibility 1069
thumb_up 0
access_time 2 years ago

In this article, I'm going to show you how to install Jupyter in Windows and then install .NET kernel for Jupyter notebooks. It also shows a machine learning example using ML.NET. The target audience are .NET developers who want to expand their skills in data engineering and science domain with ...

visibility 63
thumb_up 0
access_time 2 years ago

This code snippet shows how to convert string to date.

visibility 147
thumb_up 0
access_time 4 months ago

Language-Integrated Query (LINQ) is a set of technologies based on the integration of query capabilities directly into the C# or VB language in .NET. It allows intuitive query against SQL databases, XML, object list, etc.  This article shows how to return a top N records randomly.  The ...