How the pattern works
| Part | Meaning |
|---|---|
< | Opening angle bracket |
\/? | Optional slash for closing tags |
[A-Za-z][A-Za-z0-9-]* | Tag name, including custom elements like my-card |
(?:\s[^<>]*)? | Optional attributes |
\/?> | Optional self-closing slash and the closing bracket |
Code examples
JavaScript
const matches = text.match(/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?\/?>/g) ?? [];Python
import re
matches = re.findall(r'</?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?/?>', text)PHP
preg_match_all('/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?\/?>/', $text, $m);
$matches = $m[0];
Notes and limitations
Fine for quick searches and highlighting, but regex can’t parse HTML reliably (comments, scripts, attributes containing >). Use DOMParser or a real parser for anything important. To strip tags and keep the text, see remove HTML tags with regex.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex to match HTML tags?
/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?\/?>/g — it finds every match in a text. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.