MIME Type Regex for Java
/^(?: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 Java. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// MIME Type
// ReDoS-safe | RegexVault — Web & Network > Misc
import java.util.regex.Pattern;
public class MimeTypeValidator {
private static final Pattern PATTERN =
Pattern.compile("^(?: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})*$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("text/html")); // true
}
}Test 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 Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. 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