Go (RE2)

MIME Type in GO

Validate MIME media type strings like text/html, application/json, or image/png; charset=utf-8.

Try it in the GO tester →

Pattern

regexGO
^([a-z]+)\/([a-z0-9][a-z0-9!#$&\-^_.]*)(?:;\s*[a-z]+=\S+)*$   (flags: i)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?i)^([a-z]+)\/([a-z0-9][a-z0-9!#$&\-^_.]*)(?:;\s*[a-z]+=\S+)*$`)
	input := `application/json`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

Group 1 captures the primary type (text, image, application, etc). Group 2 captures the subtype using the allowed MIME subtype character set. The optional trailing group (?:;\s*[a-z]+=\S+)* matches parameters like charset=utf-8 or boundary=something.

Examples

Input

application/json

Matches

  • application/json

Input

text/html; charset=utf-8

Matches

  • text/html; charset=utf-8

Input

not a mime type

No match

Same pattern, other engines

← Back to MIME Type overview (all engines)