3

I can't seem to get rid of the backslash (\) from a string. Read tons of different answers to this question but none of them seems to work for me. Consider following example (the trials below are taken from various answers to similar question in stackoverflow):

temp = "35:12:34\"}}}\"}"
gsub("\\","",temp)

Error in gsub("\", "", temp) : invalid regular expression '\', reason 'Trailing backslash'

gsub("\\","",temp,fixed=T)

[1] "35:12:34\"}}}\"}"

gsub("\\\\","",temp,fixed=T)

[1] "35:12:34\"}}}\"}"

gsub("([\\])","",temp)

[1] "35:12:34\"}}}\"}"

gsub("([\\])","",temp,fixed=T)

[1] "35:12:34\"}}}\"}"

Would appreciate help to get rid of this backslash.

agondiken
  • 863
  • 1
  • 11
  • 17

1 Answers1

2

Use this

cat(gsub("\\\"","",temp))

It will print the desired output, If you wish to store it as an object use

text <- capture.output(cat(gsub("\\\"","",temp)))

But while printing text the quotes will be escaped again. but you can verify the number of characters by nchar(text)

> text <- capture.output(cat(gsub("\\\"","\"",temp)))
> text
[1] "35:12:34\"}}}\"}"
> cat(text)
35:12:34"}}}"}
> nchar(text)
[1] 14
Vikram Venkat
  • 663
  • 4
  • 16