C# Regex - Remove Heading Tags

access_time 2 months ago visibility9 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

Want to publish your article on Kontext?

Learn more

Kontext Column

Created for everyone to publish data, programming and cloud related articles.
Follow three steps to create your columns.


Learn more arrow_forward

More from Kontext

local_offer C#

visibility 468
thumb_up 0
access_time 3 years ago

Tuple is an ordered sequence, fixed-size, immutable and of heterogeneous objects. Tuple has been existing in other languages such as F#, Python, Perl and etc. for a long time. It was first introduced into C# from C# 4.0 and has been evolving over time. Since C# 7.1, tuple has become very easy to ...

local_offer C# local_offer .NET

visibility 178
thumb_up 0
access_time 12 months ago

JSON is commonly used in modern applications for data storage and transfers. Pretty much all programming languages provide APIs to parse JSON. 

local_offer asp.net core local_offer C#

visibility 257
thumb_up 0
access_time 2 months ago

Microsoft 365 and Office 365 supports using licensed user account to send emails in client applications. SMTP protocol can be used to send emails in ASP.NET Core applications. This article shows how to use SMTP AUTH to send emails in ASP.NET Core 3.1 applications. warning  This guide is ...

About column

Code snippets and tips for various programming languages/frameworks.

rss_feed Subscribe RSS