从文件路径中提取文件扩展名
如何提取给定文件路径的文件扩展名作为字符?我知道我可以通过正则表达式 regexpr("\\.([[:alnum:]]+)$", x) 来做到这一点,但想知道是否有一个内置函数可以处理这?
How can I extract the extension of a file given a file path as a character? I know I can do this via regular expression regexpr("\\.([[:alnum:]]+)$", x)
, but wondering if there's a built-in function to deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用 R 基本工具很容易找到这种东西。例如:??路径。
不管怎样,加载
tools
包并读取?file_ext
。This is the sort of thing that easily found with R basic tools. E.g.: ??path.
Anyway, load the
tools
package and read?file_ext
.让我从 https://stackoverflow.com/users/680068/zx8754 扩展一点很好的答案,
这是简单的代码片段
结果应该是“txt”。
Let me extend a little bit great answer from https://stackoverflow.com/users/680068/zx8754
Here is the simple code snippet
The result should be 'txt'.
简单的功能,无需加载包:
simple function with no package to load :
如果扩展名包含非 alnum,上面的正则表达式将失败(参见例如 https://en.wikipedia.org/维基/文件扩展名列表)
作为替代方法,可以使用以下函数:
}
The regexpr above fails if the extension contains non-alnum (see e.g. https://en.wikipedia.org/wiki/List_of_filename_extensions)
As an altenative one may use the following function:
}
仅提取不带点的文件扩展名:
tools::file_ext(fileName)
提取带点的文件扩展名:
paste0(".", tools::file_ext(fileName))
extract file extension only without dot:
tools::file_ext(fileName)
extract file extension with dot:
paste0(".", tools::file_ext(fileName))
一种方法是使用
sub
。假设有一个点 - 如果没有扩展名,则会失败:
用于比较
tools::file_ext(s)
和内部使用正则表达式的代码。A way would be to use
sub
.Assuming there is a dot - which will fail in case there is no extension:
For comparison
tools::file_ext(s)
and the code with inside used regex.如果您不想使用任何额外的包,您可以尝试
如果您喜欢神秘,您可以尝试将其用作单行表达式:
sub("^(.*\\.|[^. ]+)(?=[^.]*)", "", filenames, perl = TRUE)
;-)它适用于零个 (!)、一个或多个文件名(作为字符向量或列表)具有任意数量的点
.
,也适用于没有任何扩展名的文件名,它返回空字符""
。这里是我尝试过的测试:
顺便说一句,
tools::file_ext()
很难找到带有非字母数字字符的“奇怪”扩展名:If you don't want to use any additional package you could try
If you like to be cryptic you could try to use it as a one-line expression:
sub("^(.*\\.|[^.]+)(?=[^.]*)", "", filenames, perl = TRUE)
;-)It works for zero (!), one or more file names (as character vector or list) with an arbitrary number of dots
.
, and also for file names without any extension where it returns the empty character""
.Here the tests I tried:
By the way,
tools::file_ext()
has trouble finding "strange" extensions with non-alphanumeric characters:该函数使用管道:
This function uses pipes:
我发现没有额外的包的最简单的方法:
Simplest way I've found with no additional packages: