PatternRegex
Match an HTML tag
Find opening and closing HTML tags in text — for stripping, counting or spotting markup — and the famous reason regex must never parse HTML.
Last updated
Matches
- <div>
- </p>
- <img src="logo.png">
- <custom-element>
Doesn’t match
- <>
- <1div>
- a < b
Why it’s written this way
An optional slash covers closing tags, the name must start with a letter (so a stray < in "a < b" can't start a match), and the optional attribute chunk requires a leading space then anything that isn't an angle bracket — which is what keeps the match from running past the tag's own >.
The [\w-]* name body accepts custom elements like <my-widget> for free.
Edge cases to know
- →This finds tag-shaped substrings; it does not parse HTML. Nesting, comments, CDATA and attribute values containing > all defeat any regex — for real parsing use a DOM parser.
- →Attribute values holding an angle bracket (title="a>b") end the match early at that >.
- →It matches tags inside code samples and escaped text too — strip or segment first if that matters.