Web
HTML Tag Regex
This pattern finds individual HTML tags such as <div>, </p> or <img src="a.png" />, capturing the tag name in group 1. It requires the name to start with a letter, so comparisons like a < b are not mistaken for tags, and it allows attributes after a whitespace character. It is useful for quick audits, counting tags in templates, stripping markup from short snippets and search-and-replace in editors. The honest limit is the usual one: HTML is not a regular language, so attributes containing > characters, comments and scripts can confuse it. Use a real HTML parser for anything important.
Pattern (JavaScript)
/</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>/Matches the character "<", then the character "/", optionally (zero or one time), then a group (a letter, then one of the characters A-Za-z0-9-, zero or more times), then (a whitespace character (space, tab, newline), then any character except <>, zero or more times), optionally (zero or one time), then the character "/", optionally (zero or one time), then the character ">".
Examples
Matches
- ✓ <div>
- ✓ </p>
- ✓ <img src="a.png" />
Does not match
- ✗ a < b > c
- ✗ <>
- ✗ <3 hearts
Try it
3 matches (JavaScript engine)
<div> </p> <img src="a.png" /> a < b > c <> <3 hearts
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /<\/?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?\/?>/g;
const text = "<div>";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>')
text = '<div>'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '#</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>#';
$text = '<div>';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("</?([A-Za-z][A-Za-z0-9-]*)(?:\\s[^<>]*)?/?>");
String text = "<div>";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>`)
text := "<div>"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>");
var text = "<div>";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"</?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?/?>").unwrap();
let text = "<div>";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /<\/?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?\/?>/
text = '<div>'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Can I safely strip HTML with this pattern?
- For trusted, simple snippets it works well. For untrusted input, use a proper sanitiser, because crafted markup can slip through a regex and lead to cross-site scripting.
- How do I match only a specific tag like a?
- Replace the name group with the tag you want and a word boundary, for example </?a\b[^<>]*>. Add the i flag to match uppercase tags too.
- Does it match HTML comments?
- No, comments start with <! and the pattern requires a letter or slash after <. Use a separate pattern such as <!--[\s\S]*?--> for comments.
Related patterns
- Data URI^data:([a-z]+/[a-z0-9.+-]+)?(?:;[a-z0-9-]+=[a-z0-9-]+)*(;base64)?,[A-Za-z0-9+/=%._~-]*$
- URL Query Parameter[?&]([A-Za-z0-9_.-]+)=([^&#\s]*)
- Domain Name^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$
- File Path with Extension^(?:[A-Za-z]:[\\/]|/)?(?:[\w .-]+[\\/])*[\w .-]+\.[A-Za-z0-9]{1,8}$