You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中按顺序用字符向量替换字符串中的问号

问题描述

给定两个字符串:

seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"

需要按bb_seq的字符顺序替换seed_pattern中的所有?,最终得到结果:

KrEDhhHRDDKDKDhHEhREKEitDEvKKK

已知seed_pattern中?的总长度与bb_seq长度一致。尝试了以下代码但未成功:

seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"
sp <- seed_pattern
gr   <- gregexpr("\\?+", sp)
csml <- lapply(gr, function(sp) cumsum(attr(sp, "match.length")))
regmatches(sp, gr) <- lapply(csml, function(sp) substring(bb_seq, c(1, sp[1]), sp))
sp
# 输出错误结果:KrEDrhhHRDDKDKDrhhhHErhhhhREKErhhhhitDErhhhhitvKKK

寻求可行的R语言实现方案,接受非正则表达式方法。

可行解决方案

方法一:正则匹配+按段截取替换

核心思路是定位所有连续?的片段,按片段长度从bb_seq中按顺序截取对应子串完成替换:

seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"

# 获取所有连续?的匹配位置与长度
match_info <- gregexpr("\\?", seed_pattern)[[1]]
match_lengths <- attr(match_info, "match.length")

# 计算bb_seq的截取起止位置
start_pos <- c(1, cumsum(match_lengths)[-length(match_lengths)] + 1)
end_pos <- cumsum(match_lengths)

# 截取对应替换子串并完成替换
replace_strings <- mapply(function(s, e) substring(bb_seq, s, e), start_pos, end_pos)
regmatches(seed_pattern, gregexpr("\\?+", seed_pattern)) <- list(replace_strings)

seed_pattern
# 输出:[1] "KrEDhhHRDDKDKDhHEhREKEitDEvKKK"

方法二:拆分字符逐个替换(非正则)

将两个字符串拆分为单个字符,遍历seed_pattern的字符,遇到?就从bb_seq中按顺序取字符替换:

seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"

# 拆分为字符向量
seed_chars <- strsplit(seed_pattern, "")[[1]]
bb_chars <- strsplit(bb_seq, "")[[1]]

# 遍历替换
bb_idx <- 1
for (i in seq_along(seed_chars)) {
  if (seed_chars[i] == "?") {
    seed_chars[i] <- bb_chars[bb_idx]
    bb_idx <- bb_idx + 1
  }
}

# 合并为结果字符串
result <- paste(seed_chars, collapse = "")
result
# 输出:[1] "KrEDhhHRDDKDKDhHEhREKEitDEvKKK"

方法三:使用stringr包简化操作

借助stringr包的str_replace_all函数,结合自定义替换逻辑实现:

library(stringr)

seed_pattern <- "K?ED??HRDDKDKD?HE?REKE??DE?KKK"
bb_seq <- "rhhhhitv"

bb_chars <- strsplit(bb_seq, "")[[1]]
bb_idx <- 1

result <- str_replace_all(seed_pattern, "\\?", function(x) {
  bb_idx <<- bb_idx + 1
  bb_chars[bb_idx - 1]
})

result
# 输出:[1] "KrEDhhHRDDKDKDhHEhREKEitDEvKKK"

内容的提问来源于stack exchange,提问作者littleworth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:50:35