gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:21:45 27 4
gpt4 key购买 nike

假设你想用向量替换中的第二个元素替换第二个字符串匹配。例如:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com