[英]Regular Expression for Extension of File
我需要1个正则表达式来使用它的扩展名来限制文件类型。
我试过这个来限制html,.class等的文件类型。
/(\\.|\\/)[^(html|class|js|css)]$/i
/(\\.|\\/)[^html|^class|^js|^css]$/i
我需要限制总共10-15种类型的文件。 在我的应用程序中,有一个接受文件类型的字段,根据要求,我有要限制的文件类型。 所以我需要一个正则表达式,仅使用否定文件类型的否定。
插件代码如下:
$('#fileupload').fileupload('option', {
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|txt)$/i
});
我可以指定acceptedFileType但我已经给出了限制一组文件的要求。
试试/^(.*\\.(?!(htm|html|class|js)$))?[^.]*$/i
在这里试试: http : //regexr.com?35rp0
它也适用于无扩展文件。
正如所有正则表达式一样,解释起来很复杂......让我们从最后开始
[^.]*$ 0 or more non . characters
( ... )? if there is something before (the last ?)
.*\.(?!(htm|html|class|js)$) Then it must be any character in any number .*
followed by a dot \.
not followed by htm, html, class, js (?! ... )
plus the end of the string $
(this so that htmX doesn't trigger the condition)
^ the beginning of the string
这个(?!(htm|html|class|js)
被称为零宽度负向前瞻。它在SO上每天至少解释10次,所以你可以看到任何地方:-)
您似乎误解了角色类的工作原理。 字符类仅匹配单个字符。 选择的角色是那里的所有角色。 那么,你的角色类:
[^(html|class|js|css)]
不符合html
或class
的顺序。 它只匹配该类中所有不同字符中的单个字符。
也就是说,对于您的特定任务,您需要使用负面预测 :
/(?!.*[.](?:html|class|js|css)$).*/
但是,我还会考虑使用我各自语言的String库,而不是使用正则表达式来完成此任务。 您只需要测试字符串是否以任何扩展名结尾。
如果您愿意使用JQuery,您可以考虑一起跳过正则表达式并改为使用有效扩展数组:
// store the file extensions (easy to maintain, if changesa are needed)
var aValidExtensions = ["htm", "html", "class", "js"];
// split the filename on "."
var aFileNameParts = file_name.split(".");
// if there are at least two pieces to the file name, continue the check
if (aFileNameParts.length > 1) {
// get the extension (i.e., the last "piece" of the file name)
var sExtension = aFileNameParts[aFileNameParts.length-1];
// if the extension is in the array, return true, if not, return false
return ($.inArray(sExtension, aValidExtensions) >= 0) ? true : false;
}
else {
return false; // invalid file name format (no file extension)
}
这里的最大优点是易于维护。 。 。 更改可接受的文件扩展名是对阵列的快速更新(甚至是属性或CMS更新,具体取决于花哨的东西:))。 此外, regex
有一个过程密集的习惯,所以这应该更有效(但是,我还没有测试过这个特例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.