Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for finding valid filename

I want to check whether a string is a file name (name DOT ext) or not.

Name of file cannot contain / ? * : ; { } \

Could you please suggest me the regex expression to use in preg_match()?

like image 733
OrangeRind Avatar asked Jun 23 '09 11:06

OrangeRind


People also ask

How do I validate a file name using regex?

File name validation can be done by writing an appropriate regex pattern according to the file name requirements you have. For the purpose of this example, let’s assume that the file name may contain only letters, numbers, hyphens (“-“), underscores, dots (“.”), and spaces.

How do I use a regular expression to match a filename?

A regular expression to match valid filenames. It can be used to validate filenames entered by a user of an application, or the filename of files uploaded from a scanner. The expression ensures that your filename conforms to specific rules, including no leading or trailing spaces and no use of any characters besides the letters A-Z and numbers 0-9.

Why does the third file name fail regex validation?

The third file name does not have an extension, similarly, the fourth file name only has an extension so both of them fail in the validation. The rest of the file names passed the regex validation as they fulfill all the criteria.

What does valid file name mean?

Valid file name mean it can contain lowercase letters, uppercase letters, digits, _ (underscore), - (hyphen), . (dot for ectension) and also can contain white spaces. Mean no special characters are allowed other than white spaces, underscore, hyphen and dot. There are some Mathes for example.


2 Answers

Here you go:

"[^/?*:;{}\\]+\\.[^/?*:;{}\\]+"

"One or more characters that aren't any of these ones, then a dot, then some more characters that aren't these ones."

(As long as you're sure that the dot is really required - if not, it's simply: "[^/?*:;{}\\]+"

like image 181
RichieHindle Avatar answered Oct 30 '22 09:10

RichieHindle


$a = preg_match('=^[^/?*;:{}\\\\]+\.[^/?*;:{}\\\\]+$=', 'file.abc');

^ ... $ - begin and end of the string
[^ ... ] - matches NOT the listed chars.
like image 22
hegemon Avatar answered Oct 30 '22 08:10

hegemon