Home » Replace or remove backslashes in a string in R

Replace or remove backslashes in a string in R

  • by
  • 2 min read
Tags:

Escape ’til infinity — removing or replacing backslashes in a string can be burdensome in any programming language, if you’re not familiar what regex library is below the hood. In this post, we’ll remove a backslash from a string in R.

Perhaps the most valuable resource of all
all credits to xckd

Using gsub, there’s two paradigms to choose from. The first is by selecting it via a regex pattern. Believe it or not, but you’ll have to provide four (!) backslashes. This is because all characters are first parsed by the R parser, before being sent to the command line — i.e. you have to escape the escape.

my_str <- 'I am a \ backslash'
my_str <- gsub(
  pattern = ('\\\\'), 
  replacement = '', 
  x = my_str
  )

However, there’s a less confusing way. Instead of using regex patterns, you can simply match literal strings by using gsub‘s fixed parameter.

my_str <- gsub(
  pattern = ('\\'), 
  replacement = '', 
  x = my_str,
  fixed = T
)

You can also do it using stringr:

str_replace(my_str, fixed("\\"), "backslash")

Let me know in the comments below if you figured this out.

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

Your email address will not be published. Required fields are marked *