我有一个向量vec
。我需要删除最后一个“ /”之前的部分,并获取剩余的字符串并获取result
。另请注意,我不能使用与Perl兼容的正则表达式(即perl = FALSE)。我也希望在第n个定界符中看到它。
vec<-c("/apple/pineapple/mango/reg.sh_ttgs.pos","/apple/pipple/mgo/deh_ttgs.pos")
最后一个定界符的结果
reg.sh_ttgs.pos , deh_ttgs.pos
第二个定界符的结果
pineapple/mango/reg.sh_ttgs.pos, pipple/mgo/deh_ttgs.pos
等等..
一种方法是使用这样的函数(gregexpr
用于获取字符串的位置并相应substring
地子集字符串):
get_string <- function(vec, n) {
if(n == 'last'){
positions <- lapply(gregexpr(pattern ='/',vec), function(x) x[length(x)] + 1)
}else{
positions <- lapply(gregexpr(pattern ='/',vec), function(x) x[n] + 1)
}
substring(vec, positions)
}
输出:
> get_string(vec, 2)
[1] "pineapple/mango/reg.sh_ttgs.pos" "pipple/mgo/deh_ttgs.pos"
> get_string(vec, 'last')
[1] "reg.sh_ttgs.pos" "deh_ttgs.pos"
您可以指定第n个“ /”,也可以仅指定“最后一个”(如果只需要路径的最后一部分)。
注意:我在if-else
上面使用一条语句,以防最后一个'/'的位置在实际向量的各个元素中不同。如果/
s的数量在所有元素中始终相同,则仅lapply(gregexpr(pattern ='/',vec), function(x) x[n] + 1)
需要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句