【问题标题】:Google Drive API: find a file by name using wildcards?Google Drive API:使用通配符按名称查找文件?
【发布时间】:2026-02-11 12:50:01
【问题描述】:

使用 Google Drive API v3 时,是否可以使用通配符或正则表达式按文件名搜索文件? The docs什么都别提。

我正在尝试匹配一组名称具有以下格式的文件

backup_YYYY-MM-DD-XXXX_NameOfWebsite_xxxxxxxxxx.zip

我想知道构建可能匹配它的模式的最佳方法是什么。当然,我可以按照文档进行操作,然后执行以下操作:

q="name contains 'backup' and name contains 'NameOfWebsite'"

但如果我需要匹配不同的模式,或者文件名中有超过 2 个不同字符串的东西("backup_""NameOfWebsite"),您可以快速了解以这种方式构造查询是多么痛苦:

q="name contains 'string1' and name contains 'string2' and name contains...

【问题讨论】:

  • 你不能把你的字符串变量传入你的查询字符串吗?如果* 是通配符,则执行q="name contains 'backup' and name contains 'NameOfWebsite'" 与执行q="name = '*backup*NameOfWebsite*'" 相同。
  • 您不能在 q 搜索词中使用通配符。您必须对 name contains 查询进行字符串处理。
  • 也来自文档:The contains operator only performs prefix matching for a name. For example, the name "HelloWorld" would match for name contains 'Hello' but not name contains 'World'. 因此,如果前面没有空格,则不能在文件名中间使用name contains 'NameOfWebsite'。阅读更多关于包含here

标签: google-drive-api


【解决方案1】:

答案:

在使用 q 参数发出 Drive.list 请求时,不能在文件名中间使用通配符。

更多信息:

name 字段只需要三个运算符 - =!=contains

  • = 运算符是正则等价运算符,因此不能使用通配符。
  • name = 'backup*' 不会返回任何结果。
  • != 运算符不等价,此处不相关,但与 = 相反
  • contains 运算符。您可以使用通配符,但有限制:
  • name contains 'backup*' 将返回文件名字符串backup 开头的所有文件。
  • name contains '*NameOfWebsite' 将返回文件名以字符串NameOfWebsite 开头的所有文件。文件名backup0194364-NameOfWebsite.zip不会返回,因为字符串前没有空格

因此,唯一可行的方法就是按照你已经开始意识到的方式去做;字符串链接:

name contains 'backup' and name contains 'NameOfWebsite' and name contains ...

参考资料:

【讨论】: