4

I have to filter filenames to match only image (png,jpg,gif,bmp) files, is possible to make a such regex or do I have to have different regex for every file type? It also cannot contain path like ../../ or /var/app/filename.exe etc.

4
  • From where are you getting this file paths? From browser? From FileDialog? Commented Aug 18, 2011 at 5:43
  • So you want to make validation in javascript? Commented Aug 18, 2011 at 5:52
  • No, in Java server side. Commented Aug 18, 2011 at 6:23
  • Request is made like this myserverurl?filename=imagefilename.png Commented Aug 18, 2011 at 6:24

4 Answers 4

12

I'll use something like this... This should cover most cases without going too much into crazy details...

(.*/)*.+\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$

As a Java String this regex looks like this:

"(.*/)*.+\\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP|JPEG)$"

Hope that helps... :)

Sign up to request clarification or add additional context in comments.

Comments

4

Link:

http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/

I hope you find it useful.

2 Comments

I have to mention that that code must be edited if you don't want to allow paths in filenames. I used ([\w]+(\.(?i)(jpg|png|gif|bmp))$) , which means only letters and numbers are allowed in filename.
It might be useful to provide any code, with some explanation. Imagine the blog does not exist any more.
2

Pretty easy:

re = ".*\\.(png|jpg|gif|bmp)"

as long as you don't need UPPERCASE and jpeg. :)

Comments

0

This pattern is working for me: (.*/)*.+\.(png|jpg|gif|bmp|jpeg|PNG|JPG|GIF|BMP)$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.