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

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

问题描述

我有一个像这样的文件名: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天全站免登陆