简体   繁体   中英

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

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

$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:

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

在 Golang 程序中用于检查 Unix 文件名的正则表达式下方:

    reg := regexp.MustCompile("^/[[:print:]]+(/[[:print:]]+)*$")

Here is an easy to use solution with specific file extensions:

$file = 'file-name_2020.png';
$extensions = array('png', 'jpg', 'jpeg', 'gif', 'svg');
$pattern = '/^[^`~!@#$%^&*()+=[\];\',.\/?><":}{]+\.(' . implode('|', $extensions). ')$/u';

if(preg_match($pattern, $discount)) {
    // Returns true
}

Keep in mind that special characters allowed in this scenario are only - and _ . To allow more, just remove them from $pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM