user1867196
user1867196

Reputation: 115

Java regular expression for matching filenames or filetypes

I am trying to write a java regular expression where my application should restrict the names of the files or filetypes mentioned in the regex from being attached to an email. I started the regex like this,

    .*\\.(?:jpeg|jpg)$.

Is this correct?. Right now it is not working(matching). Also, how can I add new file types or filenames to this expression incase if I want to expand this regex. Like say, I want to add the vcf file types also here in this regex, how should I do that? Also, If I need to add the filenames, say abc.bmp from being attached, how and where should I include that filename in this regex?. Any help is greatly appreciated as I am new to this regex.

Upvotes: 2

Views: 8258

Answers (3)

Martin Ender
Martin Ender

Reputation: 44259

The reason it's not matching is simply the . at the end. This tries to match a character after the end of the string. That, obviously, can't work. Remove it, and you should be fine. Note that you can reduce (?:jpeg|jpg) to jpe?g.

This is not saying that a regex is the right approach to this problem. I prefer jlordo's approach, as long as there is only a small amount of possible file extensions. This is just to let you know where you went wrong with the regex.

Note that either .* or $ is redundant. If you are using match it requires the pattern to match the entire string anyway. In that case you don't need to assert $ again. If you use find, then you don't need to match parts of the the string that are arbitrary anyway, so you can leave out the .*.

EDIT:

After the discussion in the comments, if you have a set of allowed extensions, plus a set of allowed specific file names, this would be the general regular expression:

^(?:.*\\.(?:all|allowed|file|extensions)|all\\.allowed|file\\.names)$

Upvotes: 0

jlordo
jlordo

Reputation: 37813

what about

if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
    // good
} else {
    // bad
}

I read your comment under m.buttners answer and propose the following:

List<String> allowedExtensions = loadExtensionsFromConfig(); // implement this
boolean isFileAllowed = false;
for (String extension : allowedExtensions) {
    if (fileName.endsWith(extension)) { // this is case sensitive!
        isFileAllowed = true;
        break;
    }
}

Upvotes: 3

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

It should be something like this:

.*\\.(jpe?g)$

Upvotes: 2

Related Questions