假设你想用向量替换中的第二个元素替换第二个字符串匹配。例如:
x <- "CBCADEFGHI"
pattern <- "(A|D|C)"
replacement <- c("X","Y","Z")
您将如何仅用相应的替换向量元素“Z”替换第二个模式匹配,即“C”,因为它是发现的第二个模式?
期望的输出:
"CBZADEFGHI"
最佳答案
希望我理解正确。这是我的想法。
## find the position of the second match
g <- gregexpr(pattern, x)[[1]][2]
## get the individual letter elements out of 'pattern'
s <- scan(text = gsub("[()]", "", pattern), sep = "|", what = "")
## replace the position 'g' in 'x' with the matched element in 'replacement'
substr(x, g, g) <- replacement[match(substr(x, g, g), s)]
## resulting in
x
# [1] "CBZADEFGHI"
关于regex - R 正则表达式 - 替换第 n 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32062854/