-
Notifications
You must be signed in to change notification settings - Fork 20
Backslash headache in str_replace() #394
Comments
That was a tough one! But I sort of have an answer. I will pursue this because I am still a bit puzzled. If you just print stuff to screen, it looks like it's not working: test <- c("hello/world", "no slashes here", "/double/slash")
str_replace_all(test, "/", "\\")
#> "helloworld" "no slashes here" "doubleslash"
str_replace_all(test, "/", "\\\\")
#> "hello\\world" "no slashes here" "\\double\\slash" But if you write those results to file and look at the files, you'll see the four backslash version is indeed working. I'll get back to you with more explanation. write(str_replace_all(test, "/", "\\"), "two.txt")
write(str_replace_all(test, "/", "\\\\"), "four.txt") Contents of two.txt:
Contents of four.txt:
I suspect this exercise wasn't meant to be this hard. |
The presence of the two backslashes in the printed result is the escaping of the backslash, which is necessary in the string. Which we can see more clearly once we store the string to file. |
Ok here's a cleaner demo. You can also process the result through library(stringr)
test <- c("hello/world", "no slashes here", "/double/slash")
str_replace_all(test, "/", "\\\\")
#> [1] "hello\\world" "no slashes here" "\\double\\slash"
cat(str_replace_all(test, "/", "\\\\"), sep = "\n")
#> hello\world
#> no slashes here
#> \double\slash
writeLines(str_replace_all(test, "/", "\\\\"))
#> hello\world
#> no slashes here
#> \double\slash |
Perhaps the most valuable resource of all: https://xkcd.com/1638/ |
So I noticed writeLines() being used to check the input in the text, but it hadn't occurred to me to use it to check the output. Thanks! |
Yep! |
First off, the text says that you need \ \ \ \ to represent a backslash within a regular expression within a string in R. Presumably this is because the string renders \ as a single , which regex thinks is an escape character without anything to escape from? Then \ \ \ \ is \ \ within regex which does give you escape-\
This seemed to work, in this section I've hit the exercise: "Replace all forward slashes in a string with backslashes."
So I set up my test vector and throw backslashes at it:
Did I use too many backslashes?
Add another character.... \ \ \ \ = \ \ but \ \ = nothing?
...unless the extra character actually needs an escape, in which case I get a backslash back???
It looks a bit like it's reading escape--escape-, which would mean that \ \ should give me an actual backslash - but it didn't! And if that's the case then if I move the quote mark so " comes before any further backslashes, I should get 'hello"\world'...
But I don't.
The heck is going on here?
The text was updated successfully, but these errors were encountered: