7

我需要 1 个正则表达式来限制使用它的扩展名的文件类型。

我试过这个来限制 html、.class 等的文件类型。

  1. /(\.|\/)[^(html|class|js|css)]$/i
  2. /(\.|\/)[^html|^class|^js|^css]$/i

我需要限制总共 10-15 种类型的文件。在我的应用程序中有一个接受文件类型的字段,并且根据要求我有要限制的文件类型。所以我只需要一个使用受限文件类型否定的正则表达式。

插件代码如下:

$('#fileupload').fileupload('option', {
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|txt)$/i
});

我可以指定接受的文件类型,但我已经给出了限制一组文件的要求。

4

3 回答 3

19

尝试/^(.*\.(?!(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 次,因此您可以在任何地方查看 :-)

于 2013-08-06T17:24:41.627 回答
2

您似乎误解了字符类的工作原理。一个字符类只匹配一个字符。选择的角色是那里所有人中的一个。所以,你的角色类:

[^(html|class|js|css)]

不匹配html或不class按顺序。它只匹配该类中所有不同字符中的单个字符。

也就是说,对于您的特定任务,您需要使用负前瞻

/(?!.*[.](?:html|class|js|css)$).*/

但是,我也会考虑在我各自的语言中使用 String 库,而不是使用正则表达式来完成此任务。您只需要测试字符串是否以任何这些扩展名结尾。

于 2013-08-06T17:21:41.717 回答
0

如果您愿意使用 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有一个有点过程密集的习惯,所以这应该更有效(虽然,我还没有测试过这个特殊情况)。

于 2013-08-06T17:39:47.397 回答