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 |
| \b | a 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.
| Input | Result | Matched |
|---|---|---|
| <p> | matches | <p> |
| </div> | matches | </div> |
| <a href="/x"> | matches | <a href="/x"> |
| <br/> | matches | <br/> |
| p> | no match | — |
| < p> | no match | — |
| plain text | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID