1

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?

lmo
  • 37,904
  • 9
  • 56
  • 69
vdvaxel
  • 667
  • 1
  • 14
  • 41
  • I don't have experience with r, but `gsub("\\([.?])","\\\\$1",x)` or `gsub("\\([.?])","\\\\\\1",x)` should work. – Aran-Fey Feb 23 '17 at 16:56
  • There is no metacharacter escape function in _r_ ? –  Feb 23 '17 at 16:56
  • 2
    Depending on your use case, you may be able to skip this step and just use the `fixed = TRUE` argument in your subsequent regex. – Gregor Thomas Feb 23 '17 at 16:59
  • I think probably you have it backwards. The target string never has to be escaped. Only the regex string string with literal metachar's (ie. `?*+`, etc) need to be escaped. –  Feb 23 '17 at 17:10
  • What are you trying to do? I don't think answering this question will help you get your real task done properly – MichaelChirico Feb 23 '17 at 17:13
  • [More good reading here](http://stackoverflow.com/a/27721009/903061). In addition to `fixed`, another easy solution would be to use `\\Q` and `\\E` at the start and end of your strings. – Gregor Thomas Feb 23 '17 at 17:21

1 Answers1

3

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.

Jaguar
  • 204
  • 1
  • 4