HTML tag regex

Regex to match HTML tags and strip them from text, and the cases where you need a real parser instead.

Pattern
/<\/?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g

Matches

  • <p>
  • <a href="/x">
  • </div>

Doesn't match

  • < p>
  • a < b
  • <3

Notes

  • Good for quick jobs like stripping tags from a trusted snippet: html.replace(/<[^>]*>/g, "").
  • Never use regex to sanitise untrusted HTML — attributes can contain >, and browsers repair broken markup. Use DOMParser or a sanitiser like DOMPurify.

Code

JavaScript

const re = /<\/?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
const all = text.match(re);

Python

import re

re.findall(r'</?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>', text)

Try it on your own input

The live tester adds the g and m flags so every line is checked separately.

Questions

Can regex parse HTML?

Not in general — HTML is not a regular language (nesting is unbounded). Regex is fine for flat, predictable snippets.

More patterns

Email regexPhone number regexURL regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regex