用于文件扩展名的正则表达式

Regular Expression for Extension of File

本文关键字:正则表达式 扩展名 文件 用于      更新时间:2023-09-26

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

我尝试这样做是为了限制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
});

我可以指定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)]

与CCD_ 5或CCD_。它只匹配该类中所有不同字符中的一个字符。

也就是说,对于你的特定任务,你需要使用消极展望

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

然而,我也会考虑在我各自的语言中使用字符串库,而不是使用regex来实现这项任务。您只需要测试字符串是否以这些扩展名中的任何一个结尾。

如果您对使用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有一个小流程密集型的习惯,所以这应该更高效(不过,我还没有测试过这个特定的案例)。