Regex to match empty HTML tags

In many cases we get empty html tags and that’s really annoying. If you want to select them with the help of regex then you came to the correct place. Here, we talk about micro questions that you hardly find on the internet. So read out and understand this tutorial to the very end.

There are two types of empty html tags like with attributes or without attributes. We have given the regex for both the situation.

Html tags without attributes like, <p></p>

Html tags with attributes like, <p class=”name”></p>

Regex to match specific empty html tags without attributes

Let’s suppose, you only wants to select empty p tag and not other empty tags then, use

<p>(\s| |<\/?\s?br\s?\/?>)*<\/?p>

This regex will also allows you to select empty html tags with space, br tag or new line.

This simple regex can be use only if the tag has not class, id or any other attribute.

Explanation of the regex

1st Capturing Group (\s| |<\/?\s?br\s?\/?>)** matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you’re not interested in the data.

Regex to match specific empty html tags with attributes

It is very easy to match empty html tags without attribute, but when tags are with attribute then we have need regex as follows,

<p class>(\s| |<\/?\s?br\s?\/?>)*<\/?p>

You can add class or id in the regex to match your empty html tag.

Regex to match any empty html tag

There are few conditions for this

  1. Without attributes (<div></div>)
  2. With attributes (<div class=”name”></div>)
  3. Empty children tags (<div><p></p></div>)

If you have any other condition then ask question here.

Without Attributes


Check on Regex101

With Attributes


Check on Regex101

With Empty Children Tags


Check on Regex101

Hope we have solved your problem. If not, then ask your questions in the comment section. We will solve this and tell you as soon as possible. Thank You.

Leave a Comment