Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for valid filename

Tags:

c#

regex

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?

like image 573
VJAI Avatar asked Aug 03 '12 10:08

VJAI


People also ask

Is a valid character in a filename?

Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ?

What are the special characters in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "."


1 Answers

This is the correct expression:

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

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

like image 166
Engineer Avatar answered Sep 23 '22 15:09

Engineer