[英]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.