[英]fnmatch function with two regex parameters
Can we use fnmatch
with two regular expressions? 我们可以将
fnmatch
与两个正则表达式一起使用吗?
For example, if I use fnmatch("file*", "*", 0)
, will it match in this case? 例如,如果我使用
fnmatch("file*", "*", 0)
,在这种情况下会匹配吗?
否。fnmatch的模式不是正则表达式-根据python标准lib文档,它们是“ Unix shell样式通配符”
For example, if I use
fnmatch("file*", "*", 0)
, will it match in this case?例如,如果我使用
fnmatch("file*", "*", 0)
,在这种情况下会匹配吗?
Yes, of course it will, once you remove the redundant third parameter: 是的,一旦删除了多余的第三个参数,它当然会:
>>> from fnmatch import fnmatch
>>> fnmatch("file*", "*")
True
However, it is not matching because it's interpreting both arguments as regular expressions; 但是,它不匹配,因为它将两个参数都解释为正则表达式。 it matches because the pattern
"*"
will match any input for filename
, including "file*"
. 之所以匹配,是因为模式
"*"
将匹配filename
任何输入 ,包括"file*"
。 You can see this in the source code : 您可以在源代码中看到:
return re_pat.match(name) is not None
name
(which is filename
, the first argument to fnmatch
) isn't being used as a regex, it's just the string that gets passed to re.match
. name
(这是filename
, fnmatch
的第一个参数)没有用作正则表达式,而只是将字符串传递给re.match
。
You can also see from the code that the second argument, the pattern
, is translated rather than being used directly as a regular expression, as the "Unix shell-style wildcards" syntax is not regex. 您还可以从代码中看到,第二个参数
pattern
是经过转换的,而不是直接用作正则表达式,因为“ Unix shell样式通配符”语法不是regex。 I suggest you read the documentation . 我建议您阅读文档 。
Can we use
fnmatch
with two regular expressions?我们可以将
fnmatch
与两个正则表达式一起使用吗?
No, we can't. 不,我们不能。
fnmatch
is for matching filenames to "shell-style" expression (not regex to be clear). fnmatch
用于将文件名与“ shell样式”表达式匹配(尚不清楚正则表达式)。 I have no idea what you're trying to accomplish, but in short, no. 我不知道您要完成什么,但总之,不。 You need to give it a specific filename and then a pattern to match it to, it doesn't try to see if two patterns are consistent.
您需要给它一个特定的文件名,然后给它一个匹配的模式,它不会尝试查看两个模式是否一致。
No, you can't use fnmatch
like that. 不,您不能那样使用
fnmatch
。 They are not regex in the way you are using it. 它们不是您使用方式的正则表达式。 You need to give it a specific filename and then a pattern to match it to, it doesn't try to see if two patterns are consistent.
您需要给它一个特定的文件名,然后给它一个匹配的模式,它不会尝试查看两个模式是否一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.