我想验证通过 API 输入的互联网类型。
你能帮忙写一个正则表达式来匹配吗?
下面的示例类型来自http://en.wikipedia.org/wiki/Internet_media_type http://en.wikipedia.org/wiki/Internet_media_type
application/atom+xml
application/EDI-X12
application/xml-dtd
application/zip
application/vnd.openxmlformats-officedocument.presentationml.presentation
video/quicktime
必须符合标准:
type / media type name [+suffix]
我最近需要比现有答案更严格地验证媒体类型。这是我根据交叉点想到的RFC 2045 第 5.1 节的语法 https://www.rfc-editor.org/rfc/rfc2045#section-5.1 and RFC 7231 第 3.1.1.1 节 https://www.rfc-editor.org/rfc/rfc7231#section-3.1.1.1(这不允许{}
标记和空格(参数之间除外)。对于类 C 语言(?:)
非捕获组:
ows = "[ \t]*";
token = "[0-9A-Za-z!#$%&'*+.^_`|~-]+";
quotedString = "\"(?:[^\"\\\\]|\\.)*\"";
type = "(application|audio|font|example|image|message|model|multipart|text|video|x-(?:" + token + "))";
parameter = ";" + ows + token + "=" + "(?:" + token + "|" + quotedString + ")";
mediaType = type + "/" + "(" + token + ")((?:" + ows + parameter + ")*)";
这最终会导致一个相当可怕的结果
"(application|audio|font|example|image|message|model|multipart|text|video|x-(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+))/([0-9A-Za-z!#$%&'*+.^_`|~-]+)((?:[ \t]*;[ \t]*[0-9A-Za-z!#$%&'*+.^_`|~-]+=(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+|\"(?:[^\"\\\\]|\\.)*\"))*)"
它捕获类型、子类型和参数,或者只是
"(application|audio|font|example|image|message|model|multipart|text|video|x-(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+))/([0-9A-Za-z!#$%&'*+.^_`|~-]+)"
省略参数。请注意,通过允许任何token
for type
(如 RFC 7231 所做的那样)而不是限制为“应用程序”、“音频”等。
在实践中,您可能需要额外限制输入IANA 注册媒体类型 https://www.iana.org/assignments/media-types/media-types.xhtml or mailcap https://manpages.debian.org/stretch/mime-support/mailcap.5.en.html或根据预期用途适合您的应用程序的特定类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)