将文件名拆分为名称、扩展名 [英] Splitting a file name into name,extension

查看:29
本文介绍了将文件名拆分为名称、扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的文件名:name1.csv,我想提取这个字符串的两个子字符串.一个将 name1 存储在一个变量中,另一个将扩展名 csv 存储在另一个变量中,而没有点.

I have the name of a file like this: name1.csv and I would like to extract two substrings of this string. One that stores the name1 in one variable and other that stores the extension, csv, without the dot in another variable.

我一直在寻找 Java 的 indexOf 之类的函数是否允许进行这种操作,但我根本没有找到任何东西.

I have been searching if there is a function like indexOf of Java that allows to do that kind of manipulation, but I have not found anything at all.

有什么帮助吗?

推荐答案

使用strsplit:

R> strsplit("name1.csv", "\.")[[1]]
[1] "name1" "csv"  
R> 

请注意,您 a) 需要对点进行转义(因为它是正则表达式的元字符)并且 b) 处理 strsplit() 返回一个通常只有第一个列表的事实元素很有趣.

Note that you a) need to escape the dot (as it is a metacharacter for regular expressions) and b) deal with the fact that strsplit() returns a list of which typically only the first element is of interest.

更通用的解决方案涉及正则表达式,您可以在其中提取匹配项.

A more general solution involves regular expressions where you can extract the matches.

对于文件名的特殊情况,您还有:

For the special case of filenames you also have:

R> library(tools)   # unless already loaded, comes with base R
R> file_ext("name1.csv")
[1] "csv"
R> 

R> file_path_sans_ext("name1.csv")
[1] "name1"
R> 

因为这些是很常见的任务(参见 shell 中的 basename 等).

as these are such a common tasks (cf basename in shell etc).

这篇关于将文件名拆分为名称、扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆