regular expression for excluding filename

Viewed 1176

i am trying to upload file with extension like .pdf or .xls i want to exclude .sh .exe , .js or .bat extension from the file name either these are end of the name or in between the file name ex. filename.exe.pdf I want it should excluded

([a-zA-Z0-9\s_\\.\-:])(?!(exe|sh|js|bat))+(.pdf|.xls)$

using above pattern if the filename is file.pdf then it is acceptable but i want if the filename is filename.exe.pdf then it should be exclude exe filename

currently with this pattern its matching till e.pdf for filename.exe.pdf

3 Answers

You may use

/^(?!.*(?:\.(?:exe|sh|js|bat)(?:\.|$))).*\.(?:pdf|xls)$/i

See the regex demo and the regex graph:

enter image description here

enter image description here

Details

  • ^ - string start
  • (?!.*(?:\.(?:exe|sh|js|bat)(?:\.|$))) - that is not followed with
    • .* - any 0+ chars other than line break chars, as many as possible
    • \. - dot
    • (?:exe|sh|js|bat) - any of the extensions listed
    • (?:\.|$) - a dot or end of string
  • .* - any 0+ chars other than line break chars, as many as possible
  • \.- dot
  • (?:pdf|xls) - pdf or xls
  • $ - end of string

Try:

^(?:[a-zA-Z0-9\s_\\.\-:](?!\.(?:exe|js|bat|sh)\.))+?(?:\.pdf|\.xls)$

demo and graph

enter image description here

You could do like:

 var file = files[0], type = file.type;
 if(type.match(/\.(pdf|xls)$/)){
   // only if .pdf or .xls
 }
Related