不幸的是我对正则表达式很烂。如果我有这样的路径:
/long/path/to/file
,我只需要提取file
。
如果有人提供
file/
我只需要file
。
如果有人提供
/file/
,我还需要file
。
我一直使用
stringr
函数作为拐杖,但这似乎是直接的 grep
领域。请帮忙?
如果我理解正确的话,你可以使用
basename
功能。
f <- "/long/path/to/file"
basename(f)
# [1] "file"
这个怎么样?
> path <- "/long/path/to/file"
> require(stringr)
> str_extract(path, "[^/]*$")
[1] "file"
很抱歉回答一个非常老的问题,但我被引导到这里寻找一种方法来仅提取完整文件名的directory部分。
这是如何提取目录的:
> f <- "/long/path/to/file"
> dirname(f)
[1] "/long/path/to"
当我尝试 dirname(f) 时,我得到了令人惊讶的毫无帮助的返回“。”所以,我尝试了 z <- getwd(), which returned the path to the working directory as a character string, which at least in my current use case is actually useful.