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

标签 regex r

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

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/

相关文章:

regex - 使用正则表达式匹配 vim 中的括号时的奇怪行为

r - plyr::ddply 错误消息:类(输出[[var]])<-类(值)中的错误:尝试在 NULL 上设置属性

r - 通过正则表达式筛选的选择性preventWarnings()

r - 我可以阻止通过 R 中的 NextMethod 传递参数吗?

objective-c - 使用 NSRegularExpression 和 NSPredicate 正确评估字符串时遇到问题

regex - 根据正则表达式对文件行进行排序

r - 在 R 中分配自定义周数

r - 检查英语词典中是否存在单词 r

php - 在这种情况下,哪个更适合匹配正则表达式或 parse_url

javascript - 如何用正则表达式表示需要取Categories = .... & Search = ..... & 的值