regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match an HTML Tag

Copy the pattern, paste your markup below, and see every tag it finds. Below the tester: what each part covers and the well-known limits of parsing HTML with regex.

/ /

What this pattern matches

This expression matches HTML tags: opening tags like <div class="box">, closing tags like </a>, and self-closing tags like <br/>, including their attributes.

How it works, part by part

</? — the opening angle bracket and an optional slash for closing tags.

[a-zA-Z][a-zA-Z0-9-]* — the tag name, starting with a letter.

(?:\s+[^<>]*?)? — optional attributes, any characters that are not angle brackets.

/?> — an optional slash and the closing bracket.

The limits of regex on HTML

This is fine for stripping or highlighting tags in simple, trusted markup. It cannot correctly parse nested structures, comments, CDATA, or attribute values that contain >. For anything security-sensitive or deeply nested, use a real HTML parser — a regex will eventually get it wrong.

Use it in your code

Python
import re
text = "<div class=\"box\"><a href=\"/x\">link</a><br/><img src=\"a.png\" alt=\"pic\"></div>"
pattern = r'''</?[a-zA-Z][a-zA-Z0-9-]*(?:\s+[^<>]*?)?/?>'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "<div class=\"box\"><a href=\"/x\">link</a><br/><img src=\"a.png\" alt=\"pic\"></div>";
const re = new RegExp(String.raw`</?[a-zA-Z][a-zA-Z0-9-]*(?:\s+[^<>]*?)?/?>`, "g");
console.log(text.match(re));

FAQ

Can it match a tag whose attribute contains a > character?

No. The attribute part excludes angle brackets, so a > inside a quoted value will end the match early. Use a parser for that case.

Does it match HTML comments?

No. Comments start with <!-- and need a separate pattern such as <!--[\s\S]*?-->.

Is regex a good way to parse HTML?

For quick stripping or highlighting of simple markup, yes. For real parsing use a DOM library; nested and malformed HTML defeats regex.