Skip to main content
Code & Markup · In-Browser Regular Expression Lab

HTML Tags Regex — Match Opening, Closing & Self-Closing HTML Tags

Matches HTML markup tags for sanitization, stripping, or token extraction.

Flags:
//g
Match Found
Load Sample:
Match Inspection & Details1 match
Match #1:<p>

Test Samples Verification Matrix

Expected Valid Samples (Should Match)

<p> Pass
<div class="hero" id="main"> Pass
</span> Pass
<img src="logo.png" alt="Logo" /> Pass

Expected Invalid Samples (Must Reject)

hello world Rejected (Pass)
5 < 10 Rejected (Pass)
x > y Rejected (Pass)
Code Implementation Generator
// JavaScript / TypeScript (ES6+)
const pattern = /<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s+[^>]*?)?\/?>/g;
const text = "<p>";

const isMatch = pattern.test(text);
console.log("Is Match:", isMatch);

if (isMatch) {
  const matches = text.match(pattern);
  console.log("Matches:", matches);
}

Regular Expression Token Breakdown

Finds opening tags `<div class='x'>`, closing tags `</div>`, and self-closing tags `<img />`. Each component of the regular expression serves a distinct syntactical purpose as mapped below:

Token PatternName / ComponentFunction & Rule
<\/?Tag startMatches < or </.
[a-zA-Z][a-zA-Z0-9]*Tag nameTag name starting with a letter.
(?:\s+[^>]*?)?AttributesOptional whitespace and attribute pairs.
\/?>Tag closeMatches > or />.

Frequently Asked Questions

Can regex safely parse nested HTML?
For simple tag stripping, regex works well. For parsing complex nested DOM trees, a proper DOMParser is recommended.
Browse All 40 Patterns