[英]R: How to match a forward-slash in a regular expression?
如何匹配正斜杠/
在 R 的正则表达式中?
如下例所示,我正在尝试在子目录中搜索 .csv 文件,并且尝试使用文字/
失败。 在基础 R 中寻找对我的正则表达式的修改,而不是为我执行此操作的 function。
# Create subdirectory in current working directory with two .csv files
# - remember to delete these later or they'll stay in your current working directory!
dir.create(path = "example")
write.csv(data.frame(x1 = letters), file = "example/example1.csv")
write.csv(data.frame(x2 = 1:20), file = "example/example2.csv")
example
子目录下all.csv文件的相对路径# This works for the example, but could mistakenly return paths to other files based on:
# (a) file name: foo/example1.csv
# (b) subdirectory name: example_wrong/foo.csv
list.files(pattern = "example.*csv", recursive = TRUE)
#> [1] "example/example1.csv" "example/example2.csv"
# This fixes issue (a) but doesn't fix issue (b)
list.files(pattern = "^example.*?\\.csv$", recursive = TRUE)
#> [1] "example/example1.csv" "example/example2.csv"
# Adding / to the end of `example` guarantees we get the correct subdirectory
# Doesn't work: / is special regex and not escaped
list.files(pattern = "^example/.*?\\.csv$", recursive = TRUE)
# Doesn't work: escapes / but throws error
list.files(pattern = "^example\/.*?\\.csv$", recursive = TRUE)
# Doesn't work: even with the \\ escaping in R!
list.files(pattern = "^example\\/.*?\\.csv$", recursive = TRUE)
上面的一些解决方案适用于正则表达式工具,但不适用于 R。 我已经检查了 SO 的解决方案(下面最相关),但似乎没有一个适用:
pattern
参数仅用于匹配文件(或目录)名称,而不是它们所在的完整路径(即使recursive
和full.names
设置为TRUE
)。 这就是为什么您的最后一种方法不起作用的原因,即使它是在正则表达式中匹配/
的正确方法。 您可以通过指定path
并将full.names
设置为TRUE
来获取正确的文件名。
list.files(path='example', pattern='\\.csv$', full.names=T)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.