-1

I have a use case where

x <- "test - hello\r\n 1...124"

and I would like to obtain "test - hello 1...124. I am aware that I can use "gsub("[\r\n]", "", x)" for this specific case. However, I am wondering how to more generally remove any backslash followed by any symbol (e.g. using something like "\." and escaping the backslash). Examples that did not work are

gsub("\.", "", x) # error
gsub("\\.", "", x) # escapes "."?
gsub("\\\.", "", x) # error 
gsub("\\\\.", "", x) # ??
...

Also I would be very thankful for an explanation as to why this is not working.

  • 1
    First and foremost, there is no backslash in `"\n"`. There is an LF char here. So what is your question about then? Replacing any newline (LF) char with an `n` char? Replacing each `"\r"` (carriage return, CR) char with an `r` char? – Wiktor Stribiżew Feb 01 '23 at 14:03
  • As stated, I would like to delete `"\r\n"` from my string by specifically deleting any occurrence of `"\"` followed by any symbol – Lukas Unterschuetz Feb 01 '23 at 14:11
  • 2
    It is not possible, the backslash exists in the string literal notation, not in the text itself. – Wiktor Stribiżew Feb 01 '23 at 14:42

2 Answers2

0

With the package strings you can use str_squish to remove not only leading and trailing whitespaces but also whitespaces somewhere in the middle.

x <- "test - hello\r\n 1...124"
stringr::str_squish(x)
#> [1] "test - hello 1...124"

gsub("\\r|\\n","", x)

gives the same result.

MarBlo
  • 4,195
  • 1
  • 13
  • 27
0

If you're looking to remove both newlines (or other escaped characters) and other strings that begin with \, you can just include both in the expression:

\r|\n|\t|\0|\\.
zmehall
  • 557
  • 3
  • 13
  • Thanks for your answer! As mentioned in the comment to the prior solution, I was looking for a general way of doing so that is not specific to `"\n"` etc. Mr Stribizew's answer makes sense, that this would not be obtainable. – Lukas Unterschuetz Feb 01 '23 at 21:56