RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex to match an HTML tag

/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi

This finds tag-shaped text, and that is genuinely useful for highlighting or for a quick count. It is not a parser: HTML permits > inside attribute values, comments and CDATA can contain anything, and nesting is not a regular language. For anything that must be correct, use a DOM parser.

What each part does

</?an opening or closing tag
[a-z][a-z0-9]*the tag name
\ba word boundary so div does not match divider
[^>]*the attributes, up to the closing angle bracket

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
<p>matches<p>
</div>matches</div>
<a href="/x">matches<a href="/x">
<br/>matches<br/>
p>no match
< p>no match
plain textno match

The mistake to avoid

Using it to strip tags from untrusted input as a security measure. An attribute containing > defeats it, and sanitising HTML with a regex is a known route to cross-site scripting.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers