繁体   English   中英

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

[英]R regex - replacing nth match

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

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

您将如何仅替换第二个模式匹配,即“C”,因为它是第二个发现的模式,具有相应的替换向量元素“Z”?

期望的输出:

"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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM