gsub and backslash

Hello,

I am trying to figure out how to substitute whatever text per a one single backslash, the final output should be a string containing one backslash.

Teoretically should be something like:

string <- "This is a string with double backslashes \\"
new_string <- gsub("\\\\", "\\", string)
new_string

But it is not forking,
anyone could give me please some light?

Thank you very much

If you use fixed = TRUE you can create a single backslash by using four backslashes as your replacement argument. It will look like you haven't changed anything by default using print() (which is what's used when you send the object name to the console), but that's because R is printing the escape characters. You can see that the output is actually different using cat().

string <- "This is a string with double backslashes \\"
new_string <- gsub("\\\\", '\\\\', string, fixed = TRUE)
new_string
#> [1] "This is a string with double backslashes \\"
cat(new_string)
#> This is a string with double backslashes \

Created on 2023-04-03 with reprex v2.0.2
More details in the StackOverflow thread, using gsub function in R to remove slash, in which I found this out

There's also another example in the following SO thread:

1 Like

Thank you Mara,

Indeed, I did what you suggest but my problem is that I need to create a string where inside the text I will include only only one backslash, I do not have to use cat().

the output I would like for exaple is " Hello my name is " but not using cat(), just print()

any idea?

Thank you

Sorry, no idea how with plain print() (though that's not to say it's impossible—someone else might know how).

The other alternative is to use writeLines(), which uses the same mechanism as cat() (i.e. doesn't print escape characters). You can see, for example, this is used in the Escaping section of the Regular Expressions vignette for stringr, since it's how you show the output unescaped.

library(stringr)
string <- "This is a string with double backslashes \\"
string
#> [1] "This is a string with double backslashes \\"
writeLines(str_replace(string, "\\\\", "\\\\"))
#> This is a string with double backslashes \

Created on 2023-04-03 with reprex v2.0.2

Edit Not sure I get your example with "Hello my name is" since that doesn't have backslashes. That would work fine with print().

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.