Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for Extension of File

I need 1 regular expression to put restrictions on the file types using it's extension.

I tried this for restricting the file type of html, .class, etc.

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

I need to restrict a total of 10-15 types of files. In my application there is a field for accepted file type, and according to the requirement I have file types which is to be restricted. So I need a regular expression using negation of restricted file type only.

The plugin code is like:

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

I can specify the acceptedFileType but i have given the requirement to restrict a set of file.

like image 804
iRunner Avatar asked Aug 06 '13 17:08

iRunner


People also ask

What is a regex file?

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *. txt to find all text files in a file manager.

Are all file extensions 3 characters?

These versions of Microsoft Windows do support file extensions that are longer than three characters. However, it is important to realize that the majority of all Microsoft programs that rely on file extensions commonly only utilize three character file extensions.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"


1 Answers

Try /^(.*\.(?!(htm|html|class|js)$))?[^.]*$/i

Try it here: http://regexr.com?35rp0

It will also work with extensionless files.

As all the regexes, it's complex to explain... Let's start from the end

[^.]*$ 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

This one (?!(htm|html|class|js) is called zero width negative lookahead. It's explained at least 10 times every day on SO, so you can look anywhere :-)

like image 66
xanatos Avatar answered Oct 26 '22 04:10

xanatos