Petr
Petr

Reputation: 1817

str_replace and keeping original pattern [r]

Is it possible to keep original pattern when using str_replace function from stringr package?

I provide an example here:

A = "Linear Model"

A %>% str_view("l$")
A %>% str_replace("l$", "(ols)")

# I need results to be Linear Model(ols)

I am fully aware that we can use paste in this perticular example however this is just reproducible example for much bigger issues I am having and need solution using stringr

Upvotes: 0

Views: 305

Answers (1)

monte
monte

Reputation: 1865

A bit of a hack, but the general idea is to find the index where the match occured, split the string into two parts from that index and insert replacement in between using 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)"

Created on 2020-06-18 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions