You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言list.files()获取以指定模式开头的文件名

解决R中list.files()仅匹配以指定字符串开头的文件问题

要只获取以test开头的文件,你需要在正则表达式中使用^锚定符,它表示匹配必须从文件名的起始位置开始。

修改后的代码如下:

# 创建测试文件(和你提供的一致)
write.csv(mtcars, "test1.csv")
write.csv(mtcars, "test2.csv")
write.csv(mtcars, "another_test1.csv")
write.csv(mtcars, "another_test2.csv")

# 匹配以test开头的文件
pattern_text <- "^test"
list.files(pattern = pattern_text)

运行结果会只返回:

[1] "test1.csv" "test2.csv"

原理说明

  • ^是正则表达式的锚点,强制匹配规则从字符串的第一个字符开始生效
  • 原代码中的"test"会匹配文件名中任意位置包含test的文件,而"^test"仅匹配以test作为开头的文件

内容的提问来源于stack exchange,提问作者Pete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:52:12