How to replace a string of characters if the pattern comes from a vector?

Viewed 115

I would like to replace a part of a string, however, I want the match to be exact. In the case bellow I want ABC to be replaced with mytag and not A to be replaced with mytag etc.

mytags <- c("A","AB","ABC","B","BB","BBC","C","CB","CBC") 
x <- "I would like to replace ABC with mytag"
stri_replace_all_fixed(x,mytags,"mytag", vectorize_all=TRUE)

[1] "I would like to replace mytagBC with mytag" "I would like to replace mytagC with mytag"  "I 
would like to replace mytag with mytag"  
[4] "I would like to replace AmytagC with mytag" "I would like to replace ABC with mytag"     "I 
would like to replace ABC with mytag"    
[7] "I would like to replace ABmytag with mytag" "I would like to replace ABC with mytag"     "I 
would like to replace ABC with mytag"

What I would like to get is:

[1] "I would like to replace mytag with mytag"
1 Answers

Here the pattern is having length greater than the vector. So, it will replicate the length of the pattern. Instead, we could create a single string pattern by concatenating with | in str_c and use that to replace so that it replace wherever any of those patterns are found

library(stringr)
str_replace_all(x, str_c("\\b(", str_c(mytags, collapse="|"), ")\\b"), "mytag")
#[1] "I would like to replace mytag with mytag"

Or another option is to pass a named vector

str_replace_all(x, setNames(rep("mytag", length(mytags)), 
       str_c("\\b", mytags, "\\b")))
#[1] "I would like to replace mytag with mytag"

The word boundary (\\b) makes sure that it won't match any partial string instead of a full word

Related