如何仅替换R中字符串的第二个字符

时间:2018-08-23 15:27:35

标签: r string substitution

s<-"HsdKjnsjsHLKsmH"

如何在R中的特定位置替换字符 将字符串s中的仅第二个“ H”替换为“ Q”

3 个答案:

答案 0 :(得分:4)

我们可以使用gregexprsubstrgregexpr查找所有匹配项并返回匹配项的位置。使用第二个匹配项的位置,然后可以使用substr将第二个“ H”替换为“ Q”。这样可以保证它始终是我们要替换的第二个“ H”:

s = "HsdKjnsjsHLKsmH"

pos <- gregexpr("H", s)[[1]][2]

substr(s, pos, pos) <- "Q"
# [1] "HsdKjnsjsQLKsmH"

使用stringr并将其设为:

的另一种方法。
library(stringr)

str_pos_replace <- function(string, pattern, replacement, pos=1){
  str_locate_all(string, pattern)[[1]][pos,, drop=FALSE] %>%
    `str_sub<-`(string, ., value = replacement)
}

str_pos_replace(s, "H", "QQQ", 2)
# [1] "HsdKjnsjsQQQLKsmH"

答案 1 :(得分:2)

s = "HsdKjnsjsHLKsmH"
sub("[^H]*H[^H]*\\KH","Q",s,perl=T)


#[1] "HsdKjnsjsQLKsmH"

答案 2 :(得分:1)

尝试以下方法。

s <- "HsdKjnsjsHLKsmH"
sub("(H[^H]*)H", "\\1Q", s)

如果要概括上面的代码,请使用以下函数。

replaceSecond <- function(s, old, new){
    pattern <- paste0("(", old, "[^", old, "]*)", old)
    new <- paste0("\\1", new)
    sub(pattern, new, s)
}

replaceSecond(s, "H", "Q")
#[1] "HsdKjnsjsQLKsmH"
相关问题