MIME Type Regex for Python
/^(?:application|audio|font|image|model|multipart|text|video|message|x-[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]{0,30})/[a-zA-Z][a-zA-Z0-9!#$&\-^_.+]{0,100}(?:;\s*[a-zA-Z][a-zA-Z0-9\-]{0,30}=[^;\s]{1,50})*$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching mime type, ported and verified for Python. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# MIME Type
# ReDoS-safe | RegexVault — Web & Network > Misc
import re
mime_type_pattern = re.compile(r'^(?:application|audio|font|image|model|multipart|text|video|message|x-[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_]{0,30})/[a-zA-Z][a-zA-Z0-9!#$&\-^_.+]{0,100}(?:;\s*[a-zA-Z][a-zA-Z0-9\-]{0,30}=[^;\s]{1,50})*$')
def validate_mime_type(value: str) -> bool:
return bool(mime_type_pattern.fullmatch(value))
# Example
print(validate_mime_type("text/html")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
text/html | html |
application/json | /json |
image/png | application/ |
audio/mpeg | text html |
text/html; charset=utf-8 | application\json |
application/vnd.ms-excel | bad-type/subtype |
x-custom/type | — |
When to use this pattern
This pattern is drawn from the Web & Network > Misc category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
MIME types are case-insensitive but should be normalized to lowercase for comparison. Never trust client-submitted Content-Type for security decisions — inspect file content directly.
Technical Notes
Top-level type is validated against IANA-defined values. x- prefix allows vendor/experimental types. Subtype may include vendor tree (vnd.), personal tree (prs.), or standard tree.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern