【发布时间】:2025-11-25 19:45:01
【问题描述】:
我对 list.files 命令中正则表达式的行为感到困惑。我有一个包含约 500 个文件的文件夹,大多数名称以“new_”开头并以“.txt”结尾。同一文件夹中还有一些其他文件,例如自述文件,_cabs.txt。
我想只获取 new_*.txt 文件。我尝试了不同的方法来调用 list.files 不同的结果。他们是:
#1 This returns ALL files including README and others
list.files(path="correctpath/")
#2 This returns ALL files including _cabs.txt, which I do not want.
list.files(path="correctpath/",pattern="txt")
#3 This returns ALL files I want, but...
list.files(path="correctpath/",pattern="new_")
#4 This returns just one of the new_*.txt files.
list.files(path="correctpath/",pattern="new*\\.txt")
#5 This returns an empty list.
list.files(path="correctpath/",pattern="new_*\\.txt")
所以我有一个可行的解决方案,但想了解方法 4 和 5 的情况。
提前致谢
拉斐尔
【问题讨论】:
-
您实际上需要转义,因为
*是一个特殊字符。所以像new_\\*.*txt或者如果没有歧义的话只是new_.*txt。无法测试,无法创建新文件。