Reputation: 745
I want to replace the punctuation in a string by adding '\\' before the punctuation. The reason is I will be using regex on the string afterwards and it fails if there is a question mark without '\\' in front of it.
So basically, I would like to do something like this:
gsub("\\?","\\\\?", x)
Which converts a string "How are you?" to "How are you\\?" But I would like to do this for all punctuation. Is this possible?
Upvotes: 1
Views: 1789
Reputation: 204
You can use gsub with the [[:punct:]] regular expression alias as follows:
> x <- "Hi! How are you today?"
> gsub('([[:punct:]])', '\\\\\\1', x)
[1] "Hi\\! How are you today\\?"
Note the replacement starts with '\\\\' to produce the double backslash you requested while the '\\1' portion preserves the punctuation mark.
Upvotes: 3