开发者

Regex: Validate that a filename does NOT end in .doc

开发者 https://www.devze.com 2023-03-04 14:01 出处:网络
I\'m trying to validate that the file does not end in .doc. I want to disallow doc and docx files from being uploaded.

I'm trying to validate that the file does not end in .doc.

I want to disallow doc and docx files from being uploaded.

This ^.*(?<!doc|开发者_开发百科docx|DOC|DOCX).*$ seems to look right, explanation-wise, but it doesn't pass..

i.e. test.jpg should be allowed... test.doc should not..

etc


Try removing the .* at the end:

^.*(?<!doc|docx|DOC|DOCX)$

although I suggest doing the opposite. You can build a regex that will match files that end with .doc, .docx, etc. and if it matches, you know it is an invalid file.

Also, as @krookedking said, you must include the \., otherwise it won't match anything that ends with doc, docx, ...


(?i).*\.docx?

You should choose the ones that don't match this pattern.


If using the regex, use ignore case. What if someone adds a file .doCx or .dOcX etc?

Your language of choice probably has some path library so you might avoid the regex altogether (I have no idea if thats possible in your case though)

Here's a small C# example:

    static void Main(string[] args)
    {
        string correctFilename = "something.xlsx";
        Debug.Assert(IsValidFile(correctFilename));

        string wrongFilename = "something.docx";
        Debug.Assert(!IsValidFile(wrongFilename));

        string wrongFilename2 = "something.doc";
        Debug.Assert(!IsValidFile(wrongFilename2));
    }

    static bool IsValidFile(string filename)
    {
        string ext = Path.GetExtension(filename).ToLower();
        return ext != ".docx"
            && ext != ".doc";
    }


My variation:

^.*(?<!\.(?i)docx?)$

The '?' makes the x optional, the (?i) makes it case-insensitive so it should match the Doc and DocX.


You could use a look ahead instead of a look behind (Lookaround rules) The look ahead below will do what you want including if it ends with docx. (unless the there is a .doc(x) file name like this test.extraperiod.doc)

^.*\.(?!doc).*$

Case insensitive

^.*\.(?!(?i)doc).*$

This look ahead can resolve the test.extraperiod.doc problem

^((?!\.(?i)docx?).)*$
0

精彩评论

暂无评论...
验证码 换一张
取 消