Regular expression for valid filename

I already gone through some question in StackOverflow regarding this but nothing helped much in my case.

I want to restrict the user to provide a filename that should contain only alphanumeric characters, -, _, . and space.

I'm not good in regular expressions and so far I came up with this ^[a-zA-Z0-9.-_]$. Can somebody help me?


This is the correct expression:

string regex = @"^[\w\-. ]+$";

\w is equivalent of [0-9a-zA-Z_].


To validate a file name i would suggest using the function provided by C# rather than regex

if (filename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
}

While what the OP asks is close to what the currently accepted answer uses (^[\w\-. ]+$), there might be others seeing this question who has even more specific constraints.

First off, running on a non-US/GB machine, \w will allow a wide range of unwanted characters from foreign languages, according to the limitations of the OP.

Secondly, if the file extension is included in the name, this allows all sorts of weird looking, though valid, filenames like file .txt or file...txt.

Thirdly, if you're simply uploading the files to your file system, you might want a blacklist of files and/or extensions like these:

web.config, hosts, .gitignore, httpd.conf, .htaccess

However, that is considerably out of scope for this question; it would require all sorts of info about the setup for good guidance on security issues. I thought I should raise the matter none the less.

So for a solution where the user can input the full file name, I would go with something like this:

^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9_-]+$

It ensures that only the English alphabet is used, no beginning or trailing spaces, and ensures the use of a file extension with at least 1 in length and no whitespace.

I've tested this on Regex101, but for future reference, this was my "test-suite":

## THE BELOW SHOULD MATCH
web.config
httpd.conf
test.txt
1.1
my long file name.txt

## THE BELOW SHOULD NOT MATCH - THOUGH VALID
æøå.txt
hosts
.gitignore
.htaccess