4

I want to output my R analysis with knitr, and I have a text which contains a row of underscores. I have to get them escaped, so to turn every _ into a \_.

But because the backslash is also a special character in regex, I did not find a way to actually have a single backslash inserted before each underscore. It seems that odd numbers of backslashes produce an error (I guess the last one gets paired with the underscore) but trying to escape with even numbers didn't work either.

a <- "blah _ blah ___ blah"
> gsub("_", "\\_", a)
[1] "blah _ blah ___ blah"
> gsub("_", "\\\\_", a)
[1] "blah \\_ blah \\_\\_\\_ blah"
> gsub("_", "\\\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\\\_"
> gsub("_", "\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\_"

What is the correct way? It doesn't have to use gsub and regex, but I need the escapes easily applied to a single string.

rumtscho
  • 2,474
  • 5
  • 28
  • 42
  • This question is *not* a duplicate. The answer of the other question is to use two backslashes - you can see in my text that I tried it and it does not work. – rumtscho Jan 03 '17 at 15:14
  • These are all dupes and the problem - *replacing with ``\``* - is described pretty well. Akrun answered it many times. Here is [my answer](http://stackoverflow.com/questions/41186399/replacing-white-space-with-one-single-backslash/41186646#41186646). – Wiktor Stribiżew Jan 03 '17 at 15:18
  • @WiktorStribiżew OK, sorry, got it now. The "have to run it through cat" part did confuse me indeed. – rumtscho Jan 03 '17 at 15:22

1 Answers1

3

We need to escape the \

gsub("_", "\\\\_", a)

If we print it, it is only a single \

cat(gsub("_", "\\\\_", a))
#blah \_ blah \_\_\_ blah

We can find it out with nchar

nchar("\\")
#[1] 1
akrun
  • 874,273
  • 37
  • 540
  • 662