给定以下字符串:
mystring <- "one fish two fish red fish blue fish"
以下功能允许替换单词中第n个出现的单词:
replacerFn <- function(String, word, rword, n){
stopifnot(n >0)
pat <- sprintf(paste0("^((.*?\\b", word, "\\b.*?){%d})\\b",
word,"\\b"), n-1)
rpat <- paste0("\\1", rword)
if(n >1) {
stringr::str_replace(String, pat, rpat)
} else {
stringr::str_replace(String, word, rword)
}
}
replacerFn(mystring, "fish", "dog", 1)
#[1] "one dog two fish red fish blue fish"
replacerFn(mystring, "fish", "dog", 2)
#[1] "one fish two dog red fish blue fish"
replacerFn(mystring, "fish", "dog", 3)
#[1] "one fish two fish red dog blue fish"
replacerFn(mystring, "fish", "dog", 4)
#[1] "one fish two fish red fish blue dog"
我们如何调整此功能以替换单词的第n个到最后一个出现?
倒数第二:
"one fish two dog red dog blue dog"
倒数第三:
"one fish two fish red dog blue dog"
等等 ...?
我尝试了诸如str_replace_all之类的操作或调整了正则表达式的部分{1,},但均未成功。
谢谢你的帮助!
这是一个更简单的选择 gsubfn
library(gsubfn)
replacerFn2 <- function(String, word, rword, n) {
p <- proto(fun = function(this, x) if (count >= n) rword else x)
gsubfn(word, p, String)
}
replacerFn2(mystring, "fish", "dog", 2)
#[1] "one fish two dog red dog blue dog"
replacerFn2(mystring, "fish", "dog", 3)
#[1] "one fish two fish red dog blue dog"
replacerFn2(mystring, "fish", "dog", 4)
#[1] "one fish two fish red fish blue dog"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句