替换字符串/文本中出现的“从第 n 个到最后一个"单词 [英] Replace 'from nth to the last' occurrence of word in string/text
本文介绍了替换字符串/文本中出现的“从第 n 个到最后一个"单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下字符串:
mystring <- "one fish two fish red fish blue fish"
以下函数允许替换其中第 n 次出现的单词:
The following function allows to replace the nth occurrence of a word in it:
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 次到最后一次出现的单词?
How do we have to adjust this function to replace the nth to last occurrence of the word?
倒数第二:
"one fish two dog red dog blue dog"
倒数第三:
"one fish two fish red dog blue dog"
等等......?
我尝试了 str_replace_all 或调整正则表达式部分 {1,} 之类的方法,但没有成功.
I tried things like str_replace_all or adjusting the regex part {1,} but without success.
感谢您的帮助!
推荐答案
这里有一个更简单的选项 gsubfn
Here is an easier option with 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"
这篇关于替换字符串/文本中出现的“从第 n 个到最后一个"单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文