Немного хака, но общая идея состоит в том, чтобы найти индекс, в котором произошло совпадение, разделить строку на две части из этого индекса и вставить замену между ними, используя paste
.
library(stringr)
library(reprex)
#> Warning: package 'reprex' was built under R version 3.6.3
A = "Linear Model"
str_extend = function(string, pattern, replacement){
matched_index_end = str_locate(string, pattern)[2] #[2] is to extract the end of matching string
#split given string into two and paste three elements together
first_part = str_sub(string, 1, matched_index_end)
second_part = str_sub(string, matched_index_end + 1, length(string))
paste(first_part, replacement, second_part, sep='')
}
str_extend(A, 'l$', '(ols)')
#> [1] "Linear Model(ols)"
Создано 18.06.2020 с помощью пакета . (v0.3.0)