Question

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()?

Was it helpful?

Solution

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: "[^/?*:;{}\\]+"

OTHER TIPS

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

^ ... $ - begin and end of the string
[^ ... ] - matches NOT the listed chars.

The regex would be something like (for a three letter extension):

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

PHP needs backslashes escaped, and preg_match() needs forward slashes escaped, so:

$pattern = "/^[^\\/?*:;{}\\\\]+\\.[^\\/?*:;{}\\\\]{3}$/";

To match filenames like "hosts" or ".htaccess", use this slightly modified expression:

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

Below the regex using for checking Unix filename in a Golang program :

    reg := regexp.MustCompile("^/[[:print:]]+(/[[:print:]]+)*$")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top