Regex for HTML Self-Closing Tag
Regex Pattern
<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\/?>Self-closing HTML tags like <br/>, <img/>, <input/>
Quick Answer
The regex pattern for html self-closing tag is `<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\/?>`. Self-closing HTML tags like <br/>, <img/>, <input/>. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| <br/> | ✓ Matches |
| <img src="x.jpg" /> | ✓ Matches |
| <input type="text"/> | ✓ Matches |
| <div>content</div> | ✗ No match |
| not a tag | ✗ No match |
| <> | ✗ No match |
Code Examples
javascript
const regex = /<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\\/?>/; const isValid = regex.test(value);
python
import re
pattern = r'<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\/?>'
if re.match(pattern, value):
print("valid")ruby
pattern = /<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\/?>/ if value =~ pattern puts "valid" end
php
if (preg_match('/<([a-zA-Z][a-zA-Z0-9]*)(?:\s+[^>]*)?\\/?>/', $value)) {
echo "valid";
}java
String pattern = "<([a-zA-Z][a-zA-Z0-9]*)(?:\\s+[^>]*)?\\/?>"; boolean isValid = value.matches(pattern);
Frequently Asked Questions
Related Regex Patterns
HTML Tag
Any HTML tag (opening, closing, or self-closing)
HTML Comment
HTML comment block (multi-line safe)
HTML Attribute
HTML attribute key-value pair (attr="value")
HTML Entity
HTML character entity (named or numeric)
Semantic HTML5 Tag
HTML5 semantic element tags
XML Namespace
XML namespace declaration (xmlns or xmlns:prefix)