我想从字符串中删除第三和第四个字符。
下面是一些示例数据:
HS0202
HS0902
MV0100
SUE0300
我需要返回像这样的东西
HS02
HS02
MV00
SUE00
使用gsub()
:
gsub("..(?=..$)", "", chrs, perl = TRUE)
# "HS02" "HS02" "MV00" "SUE00"
或与stringr::str_remove()
:
library(stringr)
str_remove(chrs, "..(?=..$)")
# "HS02" "HS02" "MV00" "SUE00"
您可以从最后的第一个字符提取到第四个字符,并粘贴在最后一个字符上,如下所示:
have <- c('HS0202', 'HS0902', 'MV0100', 'SUE0300')
want <- paste0(substring(have,1,nchar(have)-3),substring(have,nchar(have)))
Usingstringi
:
library(stringi)
stri_sub_replace(x, from = -4, to = -3, value = "")
[1] "HS02" "HS02" "MV00" "SUE00"
或与stringr
:
library(stringr)
str_sub(x, start = -4, end = -3) <- ""
x <- c("HS0202", "HS0902", "MV0100", "SUE0300")