php 用于查找有效文件名的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1032104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:43:12  来源:igfitidea点击:

Regex for finding valid filename

phpregexvalidationpreg-match

提问by OrangeRind

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

我想检查一个字符串是否是文件名(名称 DOT ext)。

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

文件名不能包含 / ? * : ; { } \

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

你能建议我在 preg_match() 中使用的正则表达式吗?

回答by RichieHindle

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

(只要您确定确实需要该点-如果不是,则很简单: "[^/?*:;{}\\]+"

回答by hegemon

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

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

回答by Tomalak

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

正则表达式类似于(对于三个字母的扩展名):

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

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

PHP 需要转义反斜杠,preg_match()需要转义正斜杠,所以:

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

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

要匹配像"hosts"".htaccess"这样的文件名,请使用这个稍微修改的表达式:

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

回答by user3627897

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

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

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