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

时间:2015-08-18 03:04:56

标签: regex r

假设您要将第二个字符串匹配替换为向量替换中的第二个元素。例如:

x <- "CBCADEFGHI"
pattern <- "(A|D|C)"
replacement <- c("X","Y","Z")

你将如何更换第二种模式匹配,即&#34; C&#34;因为它是第二个被发现的模式,带有相应的替换向量元素&#34; Z&#34;?

期望的输出:

"CBZADEFGHI"

1 个答案:

答案 0 :(得分: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"