For the first and last, we can use stri_replace from stringi as it has the option library(stringi) stri_replace(mystring, fixed="fish", "dog", mode="first") #[1] "one dog two fish red fish blue fish" stri_replace(mystring, fixed="fish", "dog", mode="last") #[1] "one fish two fish red fish blue dog"mode 只能有值 'first'、'last' 和 'all'.因此,其他选项不在默认功能中.我们可能必须使用 regex 选项来更改它.The mode can only have values 'first', 'last' and 'all'. So, other options are not in the default function. We may have to use regex option to change it.使用sub,我们可以对单词进行第n次替换Using sub, we can do the nth replacement of wordsub("^((?:(?!fish).)*fish(?:(?!fish).)*)fish", "\\1dog", mystring, perl=TRUE)#[1] "one fish two dog red fish blue fish"或者我们可以使用 sub('^((.*?fish.*?){2})fish', "\\1\\dog", mystring, perl=TRUE) #[1] "one fish two fish red dog blue fish"为了简单起见,我们可以创建一个函数来执行此操作Just for easiness, we can create a function to do thispatfn <- function(n){ stopifnot(n>1) sprintf("^((.*?\\bfish\\b.*?){%d})\\bfish\\b", n-1)} 并替换第n次出现的'fish',除了第一个可以使用sub或str_replaceand replace the nth occurrence of 'fish' except the first one which can be easily done using sub or the default option in str_replacesub(patfn(2), "\\1dog", mystring, perl=TRUE)#[1] "one fish two dog red fish blue fish"sub(patfn(3), "\\1dog", mystring, perl=TRUE)#[1] "one fish two fish red dog blue fish"sub(patfn(4), "\\1dog", mystring, perl=TRUE)#[1] "one fish two fish red fish blue dog"这也适用于 str_replace str_replace(mystring, patfn(2), "\\1dog") #[1] "one fish two dog red fish blue fish" str_replace(mystring, patfn(3), "\\1dog") #[1] "one fish two fish red dog blue fish"基于上面提到的模式/替换,我们可以创建一个新函数来完成大部分选项Based on the pattern/replacement mentioned above, we can create a new function to do most of the optionsreplacerFn <- 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" 这篇关于如何使用 stringr 的 replace_all() 函数替换字符串中的特定匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-15 18:23