Skip to content
Prev 387463 / 398502 Next

Problem with the str_replace function

Hi,

stringr::str_replace() treats the 2nd argument ('pattern') as a regular 
expression and some characters have a special meaning when they are used 
in a regular expression. For example the dot plays the role of a 
wildcard (i.e. it means "any character"):

   > str_replace("aaXcc", "a.c", "ZZ")
   [1] "aZZc"

If you want to treat a special character literally, you need to escape 
it with a double backslahe '\\':

   > str_replace(c("aaXcc", "aa.cc"), "a.c", "ZZ")
   [1] "aZZc" "aZZc"

   > str_replace(c("aaXcc", "aa.cc"), "a\\.c", "ZZ")
   [1] "aaXcc" "aZZc"

Turns out that parenthesis are also special characters so you also need 
to escape them:

   > str_replace("aa(X)cc", "a(X)c", "ZZ")
   [1] "aa(X)cc"

   > str_replace("aa(X)cc", "a\\(X\\)c", "ZZ")
   [1] "aZZc"

There are plenty of example in the man page for str_replace() (see 
'?str_replace') including examples showing the use of parenthesis in the 
pattern.

Hope this helps,

H.
On 3/16/21 5:34 PM, phil at philipsmith.ca wrote: