正则表达式 - 替换第n个匹配

3
假设您想用向量替换的第二个元素来替换第二个字符串匹配项。例如:
x <- "CBCADEFGHI"
pattern <- "(A|D|C)"
replacement <- c("X","Y","Z")

如果您想仅替换第二个匹配的模式,即因为它是发现的第二个模式而是“C”,应如何操作以使用相应的替换向量元素“Z”?

期望输出:

"CBZADEFGHI"

2
我不知道你是怎么选择相应的替换向量元素的? - Avinash Raj
为什么"A"没有被替换成"X",但是"C"却被替换成了"Z" - Tim Biegeleisen
@AvinashRaj 因为C是pattern中的第三个字母,而Z是replacement中的第三个元素,所以我想用Z替换C。 - alki
2
@TimBiegeleisen 这里替换的是第二个匹配项,用相应的元素进行替换。 - akrun
2
@akrun 这很清楚...感谢您指出这一点。 - Tim Biegeleisen
1个回答

8
希望我理解得正确。这是我的想法。
## 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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接