🏷️
Regex for Extract HTML Tags
Matches HTML tags and their attributes.
Understanding The Regex Pattern
/<\/?([a-zA-Z0-9]+)(?:\s+[^>]+)?>/gMatches
- <div class="test">
- </div>
- <img>
Non-Matches
- 1 < 2
- Not a tag
How this Pattern Works
Extracting or manipulating HTML tags within a raw string is a common task when building WYSIWYG editors, text parsers, or basic web scrapers. This regular expression identifies both opening and closing HTML tags, capturing the tag name (like 'div' or 'img') while ignoring any associated attributes or classes. While this pattern is useful for simple extraction tasks and syntax highlighting, developers should be cautious and use dedicated DOM parsers for complex HTML manipulation or security sanitization.
Implement The Regex In Your Code
javascript
const regex = /<\/?([a-zA-Z0-9]+)(?:\s+[^>]+)?>/g;
const str = '<div>test</div>';
const tags = str.match(regex);python
import re
regex = re.compile(r'<\/?([a-zA-Z0-9]+)(?:\s+[^>]+)?>')
tags = regex.findall('<div>test</div>')go
import "regexp"
re := regexp.MustCompile(`<\/?([a-zA-Z0-9]+)(?:\s+[^>]+)?>`)
tags := re.FindAllString(`<div>test</div>`, -1)rust
use regex::Regex;
let re = Regex::new(r"<\/?([a-zA-Z0-9]+)(?:\s+[^>]+)?>").unwrap();
let tags: Vec<_> = re.find_iter("<div>test</div>").map(|m| m.as_str()).collect();