0

I have a string that may have something similar to \1 at the end that I would like to remove.

However I'm running into some problems.

gsub('([\\0-9])', '', 'NY \2', perl = T) ## Looking for "NY". Works fine
## NY

gsub('([\\0-9])', '', 'N Y \2', perl = T) ## Looking for "N Y". Why does this remove the space?
## NY 

gsub('([\\0-9])', '', 'N Y \2', perl = F) ## Looking for "N Y". Why does this add \00?
##  N Y \002
Rafael
  • 3,096
  • 1
  • 23
  • 61
  • 1
    See [what string you test against](https://ideone.com/Aq3XF0). What is the real value? – Wiktor Stribiżew Jun 14 '18 at 19:15
  • can I save output of `cat` to an object? – Rafael Jun 14 '18 at 19:17
  • Do you mean you have `NY \2` string? `'NY \\2'`? Do you want to remove a backslash followed with a digit? `gsub("\\\\[0-9]", "", "NY \\2")`? You seem to run into the problem that you do not know what text you have and what you need to get out of it. What is your question? – Wiktor Stribiżew Jun 14 '18 at 19:19
  • I have a string that might have a backslash followed by a number. I would like to remove the backslash and the number, while preserving everything before the backslash. Including spaces, if any. – Rafael Jun 14 '18 at 19:22
  • I will close it, you just do not understand how to define a backslash in the string. – Wiktor Stribiżew Jun 14 '18 at 19:24
  • Still not quite sure about why the question was closed. The backslashes appear un-escaped in the string I'm trying to run `gsub` on--i.e. only one backslash before the digit. This ended up solving my problem: `gsub('([^a-zA-Z| ])', '', 'N Y \2', perl = F)` – Rafael Jun 14 '18 at 19:40
  • Inside `'\2'` ***string***, there is no backslash at all. If you need to remove any non-printable chars, use `gsub("[[:cntrl:]]+", "", x)`. See [`cat(gsub('[[:cntrl:]]+', '', 'N Y \2'))`](https://ideone.com/dbAYHB). Or all non-printable, `cat(gsub('[^[:print:]]+', '', 'N Y \2'))` – Wiktor Stribiżew Jun 14 '18 at 19:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/173171/discussion-between-r-m-and-wiktor-stribizew). – Rafael Jun 14 '18 at 19:41

0 Answers0