1

I would like to replace $ in my R strings. I have tried:

mystring <- "file.tree.id$HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked"

 stringr::str_replace(mystring, pattern="$", 
              replacement="!")

However, it fails and my replacement character is put as the last character in my original string:

[1] "file.tree.id$HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked!"

I tried some variation using "pattern="/$" but it fails as well. Can someone point a strategy to do that?

user3091668
  • 2,050
  • 5
  • 23
  • 38

2 Answers2

3

In base R, You could use:

chartr("$","!", mystring)
[1] "file.tree.id!HASHd15962267-44c21f1cee1057d95d6840!HASHe92451fece3b3341962516acfa962b2f!checked"

Or even

 gsub("$","!", mystring, fixed = TRUE)
onyambu
  • 49,350
  • 3
  • 19
  • 45
1

We need fixed to be wrapped as by default pattern is in regex mode and in regex $ implies the end of string

stringr::str_replace_all(mystring, pattern = fixed("$"), 
              replacement = "!")

Or could escape (\\$) or place it in square brackets ([$]$), but `fixed would be more faster

akrun
  • 789,025
  • 32
  • 460
  • 575
  • Thanks for your solution. However it seems to replace only the first `$` in the string. stringr::str_replace(mystring, pattern = fixed("$"), + replacement = "!") [1] "file.tree.id!HASHd15962267-44c21f1cee1057d95d6840$HASHe92451fece3b3341962516acfa962b2f$checked" – user3091668 Apr 21 '21 at 17:08
  • 1
    @user3091668 sorry, didn't check your string earlier. You need `str_replace_all`, because `str_replace` only does the replacement on the first instance – akrun Apr 21 '21 at 17:09