Replacing ' by \'
How to convert '
in a stri开发者_如何学编程ng to \'
in R?
Example: from Bob's
to Bob\'s
You have to escape the backslash.
> gsub("'","\\\\'","Bob's") # R prints with the escape embedded
[1] "Bob\\'s"
> cat(gsub("'","\\\\'","Bob's"),"\n") # But it's just a single backslash
Bob\'s
> gsub("'", "\\\\'", "foo's bar's")
[1] "foo\\'s bar\\'s"
The results looks like the backslashes are double-escaped, but if you check with nchars() you'll see that it's actually just single backslashes.
I finally figured it out:
gsub("\'", "\\\'", "Bob's")
What confused me was that the backslash isn't displayed.
精彩评论